paivana

HTTP paywall reverse proxy
Log | Files | Refs | Submodules | README | LICENSE

paivana-httpd_templates.c (54034B)


      1 /*
      2      This file is part of GNUnet.
      3      Copyright (C) 2026 Taler Systems SA
      4 
      5      Paivana is free software; you can redistribute it and/or
      6      modify it under the terms of the GNU Affero General Public License
      7      as published by the Free Software Foundation; either version
      8      3, or (at your option) any later version.
      9 
     10      Paivana is distributed in the hope that it will be useful,
     11      but WITHOUT ANY WARRANTY; without even the implied warranty
     12      of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
     13      the GNU Affero General Public License for more details.
     14 
     15      You should have received a copy of the GNU Affero General Public
     16      License along with Paivana; see the file COPYING.  If not,
     17      write to the Free Software Foundation, Inc., 51 Franklin
     18      Street, Fifth Floor, Boston, MA 02110-1301, USA.
     19 */
     20 
     21 /**
     22  * @author Christian Grothoff
     23  * @file paivana-httpd_templates.c
     24  * @brief template functions
     25  */
     26 #include "platform.h"
     27 #include <curl/curl.h>
     28 #include <gnunet/gnunet_util_lib.h>
     29 #include <gnunet/gnunet_uri_lib.h>
     30 #include <gnunet/gnunet_curl_lib.h>
     31 #include "paivana-httpd.h"
     32 #include "paivana-httpd_daemon.h"
     33 #include "paivana-httpd_helper.h"
     34 #include "paivana-httpd_templates.h"
     35 #include <taler/taler_mhd_lib.h>
     36 #include <taler/taler_templating_lib.h>
     37 #include "paivana_pd.h"
     38 #include <regex.h>
     39 
     40 
     41 struct Template;
     42 #define TALER_MERCHANT_GET_PRIVATE_TEMPLATE_RESULT_CLOSURE struct Template
     43 #include <taler/merchant/get-private-templates-TEMPLATE_ID.h>
     44 #include <taler/merchant/get-private-templates.h>
     45 
     46 
     47 /**
     48  * Maximum number of rendered paywall responses cached process-wide.
     49  *
     50  * A cache key is one merchant template, one installed language and one of two
     51  * compression outcomes.  256 entries cover the common case of 128 merchant
     52  * templates in one language and both encodings, while replacing the old
     53  * per-template cap whose aggregate could grow to 16,384 responses.  The exact
     54  * byte cost depends on rendered choices, so the entry cap bounds it to 256
     55  * times the largest rendered response.  On reaching it we evict the global
     56  * least-recently-used entry.
     57  */
     58 #define MAX_RESPONSE_CACHE_ENTRIES 256
     59 
     60 /**
     61  * Maximum entries accepted from `GET /private/templates'.  1024 bounds the
     62  * temporary ID list received from a shared merchant that may contain many
     63  * non-Paivana templates; only #MAX_PAIVANA_TEMPLATES survive startup.
     64  */
     65 #define MAX_DISCOVERED_TEMPLATES 1024
     66 
     67 /**
     68  * Maximum active Paivana templates.  Every request may test their regular
     69  * expressions and every template retains contract choices, so 128 bounds
     70  * both per-request CPU and long-lived memory.
     71  */
     72 #define MAX_PAIVANA_TEMPLATES 128
     73 
     74 /**
     75  * Maximum simultaneous merchant template-detail fetches during startup.
     76  * Eight keeps startup parallel without consuming the 32-descriptor payment
     77  * reserve or producing a large burst against the merchant backend.
     78  */
     79 #define MAX_TEMPLATE_FETCHES 8
     80 
     81 /**
     82  * Largest compact JSON representation accepted for one template contract.
     83  * One MiB is ample for prices and localized summaries while bounding the
     84  * contract tree retained for rendering and rejecting accidental bulk data.
     85  */
     86 #define MAX_TEMPLATE_CONTRACT_SIZE (1024 * 1024)
     87 
     88 /**
     89  * Maximum installed paywall languages recognized for cache normalization.
     90  * Thirty-two is far above a practical site translation set and bounds both
     91  * startup metadata and the language-selection loop on every cache lookup.
     92  */
     93 #define MAX_PAYWALL_LANGUAGES 32
     94 
     95 /**
     96  * How long we give the merchant backend to answer our template
     97  * queries before abandoning the startup sequence.
     98  *
     99  * Nothing is served until they are in: #PAIVANA_HTTPD_serve_requests()
    100  * — which binds the listen sockets — is only reached from the last of
    101  * these callbacks, and neither `TALER_MERCHANT_curl_easy_get_()' nor
    102  * anything above it arms CURLOPT_TIMEOUT.  A backend that accepts the
    103  * TCP connection and then never answers would otherwise leave paivana
    104  * neither serving nor exiting, with no log line after the startup
    105  * banner; under `SERVE = systemd' the listening socket already
    106  * exists, so clients connect successfully and then hang forever with
    107  * nothing accepting them.  Generous enough for the round-trips a load
    108  * takes (GET /private/templates, then one GET per template, issued in
    109  * batches of at most eight).
    110  */
    111 #define TEMPLATE_LOAD_TIMEOUT \
    112         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
    113 
    114 
    115 /**
    116  * Entry in the cache of responses for a given template.
    117  */
    118 struct ResponseCacheEntry
    119 {
    120 
    121   /**
    122    * Kept in a DLL.
    123    */
    124   struct ResponseCacheEntry *next;
    125 
    126   /**
    127    * Kept in a DLL.
    128    */
    129   struct ResponseCacheEntry *prev;
    130 
    131   /** Merchant template this rendered response belongs to. */
    132   struct Template *template;
    133 
    134   /**
    135    * Language of the response.
    136    */
    137   char *lang;
    138 
    139   /**
    140    * True if @e paywall carries a deflate-compressed body.
    141    */
    142   bool deflate;
    143 
    144   /**
    145    * Paywall response for these request parameters.
    146    */
    147   struct MHD_Response *paywall;
    148 
    149   /**
    150    * HTTP status to return with @e paywall.
    151    */
    152   unsigned int http_status;
    153 
    154 };
    155 
    156 
    157 /**
    158  * Information about a template in the merchant backend.
    159  */
    160 struct Template
    161 {
    162 
    163   /**
    164    * Kept in a DLL.
    165    */
    166   struct Template *next;
    167 
    168   /**
    169    * Kept in a DLL.
    170    */
    171   struct Template *prev;
    172 
    173   /**
    174    * ID of the template.
    175    */
    176   char *template_id;
    177 
    178   /**
    179    * Summary of the template, NULL if not given.
    180    */
    181   char *summary;
    182 
    183   /**
    184    * Maximum pickup delay for the pages.
    185    */
    186   struct GNUNET_TIME_Relative max_pickup_delay;
    187 
    188   /**
    189    * Ways how to pay for the template.
    190    */
    191   json_t *choices;
    192 
    193   /**
    194    * Regular expression of websites the template is for.
    195    */
    196   char *regex;
    197 
    198   /**
    199    * Pre-compiled regular expression @e regex.
    200    */
    201   regex_t ex;
    202 
    203   /**
    204    * Handle used to request more information about the template.
    205    */
    206   struct TALER_MERCHANT_GetPrivateTemplateHandle *gt;
    207 
    208   /**
    209    * Startup fetch state.  Detail requests are started in bounded batches
    210    * rather than all at once.
    211    */
    212   enum
    213   {
    214     TLS_WAITING,
    215     TLS_ACTIVE,
    216     TLS_DONE
    217   } load_state;
    218 
    219 };
    220 
    221 
    222 /**
    223  * Kept in a DLL.
    224  */
    225 static struct Template *t_head;
    226 
    227 /**
    228  * Kept in a DLL.
    229  */
    230 static struct Template *t_tail;
    231 
    232 /** Head of the process-wide rendered-response LRU. */
    233 static struct ResponseCacheEntry *rce_head;
    234 
    235 /** Tail of the process-wide rendered-response LRU. */
    236 static struct ResponseCacheEntry *rce_tail;
    237 
    238 /** Number of entries in the process-wide rendered-response LRU. */
    239 static unsigned int rce_length;
    240 
    241 /** Installed language tags for the `paywall' Mustache template. */
    242 static char *paywall_languages[MAX_PAYWALL_LANGUAGES];
    243 
    244 /** Number of entries in #paywall_languages. */
    245 static unsigned int paywall_languages_length;
    246 
    247 /** Template IDs waiting for a detail request to start. */
    248 static unsigned int pending_template_fetches;
    249 
    250 /** Template detail requests currently in flight. */
    251 static unsigned int active_template_fetches;
    252 
    253 /** Paivana templates retained after their contracts were inspected. */
    254 static unsigned int loaded_paivana_templates;
    255 
    256 /** Next waiting template, making bounded fetch dispatch O(T). */
    257 static struct Template *next_template_fetch;
    258 
    259 /**
    260  * Handle to get all the templates.
    261  */
    262 static struct TALER_MERCHANT_GetPrivateTemplatesHandle *gpt;
    263 
    264 /**
    265  * Watchdog for #TEMPLATE_LOAD_TIMEOUT, NULL once the templates are in
    266  * (or once we have given up on them).
    267  */
    268 static struct GNUNET_SCHEDULER_Task *load_timeout_task;
    269 
    270 
    271 /**
    272  * Task run when the merchant backend did not answer our template
    273  * queries within #TEMPLATE_LOAD_TIMEOUT.
    274  *
    275  * Treated exactly like any other failure to load the templates (an
    276  * unauthorized or unexpected status from the backend): the daemon
    277  * exits with a diagnosis instead of stalling.  Whether that policy is
    278  * the right one is a separate question — this task only makes sure the
    279  * stall is not a third, silent outcome.
    280  *
    281  * @param cls NULL
    282  */
    283 static void
    284 load_timeout (void *cls)
    285 {
    286   (void) cls;
    287   load_timeout_task = NULL;
    288   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    289               "Merchant backend at `%s' did not answer our template queries"
    290               " within %s; giving up instead of never starting to serve\n",
    291               PH_merchant_internal_url,
    292               GNUNET_STRINGS_relative_time_to_string (TEMPLATE_LOAD_TIMEOUT,
    293                                                       true));
    294   PH_global_ret = EXIT_FAILURE;
    295   GNUNET_SCHEDULER_shutdown ();
    296 }
    297 
    298 
    299 /**
    300  * The templates are in: stop the watchdog and open the listen sockets.
    301  *
    302  * Refuses to start if there is not a single one.  Only reachable with
    303  * the paywall enabled -- `-n' returns before
    304  * #PAIVANA_HTTPD_load_templates() is ever called -- and a paywall with
    305  * nothing to sell is not a paywall: PAIVANA_HTTPD_search_templates()
    306  * would answer "no template matched" for every URL, which create_response()
    307  * reads as "no paywall applies" and forwards.  The whole site would be
    308  * free, silently, which is exactly the outcome an operator running a
    309  * paywall did not ask for.  An operator who does want a plain reverse
    310  * proxy says so with `-n'.
    311  */
    312 static void
    313 templates_ready (void)
    314 {
    315   if (NULL == t_head)
    316   {
    317     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    318                 "The merchant backend at `%s' offers no paivana template;"
    319                 " refusing to start, as every request would then be"
    320                 " forwarded for free.  Pass -n if serving the site without"
    321                 " a paywall is what you want.\n",
    322                 PH_merchant_internal_url);
    323     PH_global_ret = EXIT_NOTCONFIGURED;
    324     GNUNET_SCHEDULER_shutdown ();
    325     return;
    326   }
    327   if (NULL != load_timeout_task)
    328   {
    329     GNUNET_SCHEDULER_cancel (load_timeout_task);
    330     load_timeout_task = NULL;
    331   }
    332   PAIVANA_HTTPD_serve_requests ();
    333 }
    334 
    335 
    336 /**
    337  * Check if two strings are equal, including both being NULL
    338  *
    339  * @param s1 a string, possibly NULL
    340  * @param s2 a string. possibly NULL
    341  * @return true if both are equal
    342  */
    343 static bool
    344 eq (const char *s1,
    345     const char *s2)
    346 {
    347   if (s1 == s2)
    348     return true;
    349   if (NULL == s1)
    350     return false;
    351   if (NULL == s2)
    352     return false;
    353   return (0 == strcmp (s1,
    354                        s2));
    355 }
    356 
    357 
    358 /**
    359  * Create a taler://pay-template/ URI for the given @a con and @a template_id
    360  * and @a instance_id.
    361  *
    362  * @param merchant_base_url URL to take host and path from;
    363  *        we cannot take it from the MHD connection as a browser
    364  *        may have changed 'http' to 'https' and we MUST be consistent
    365  *        with what the merchant's frontend used initially
    366  * @param template_id the template id
    367  * @return corresponding taler://pay-template/ URI, or NULL on missing "host"
    368  */
    369 static char *
    370 make_taler_pay_template_uri (const char *merchant_base_url,
    371                              const char *template_id)
    372 {
    373   struct GNUNET_Buffer buf = { 0 };
    374   char *url;
    375   struct GNUNET_Uri uri;
    376 
    377   url = GNUNET_strdup (merchant_base_url);
    378   if (-1 == GNUNET_uri_parse (&uri,
    379                               url))
    380   {
    381     GNUNET_break (0);
    382     GNUNET_free (url);
    383     return NULL;
    384   }
    385   if ( (NULL == uri.scheme) ||
    386        (NULL == uri.host) )
    387   {
    388     GNUNET_break (0);
    389     GNUNET_free (url);
    390     return NULL;
    391   }
    392   GNUNET_assert (NULL != template_id);
    393   GNUNET_buffer_write_str (&buf,
    394                            "taler");
    395   if (0 == strcasecmp ("http",
    396                        uri.scheme))
    397     GNUNET_buffer_write_str (&buf,
    398                              "+http");
    399   GNUNET_buffer_write_str (&buf,
    400                            "://pay-template/");
    401   GNUNET_buffer_write_str (&buf,
    402                            uri.host);
    403   if (0 != uri.port)
    404     GNUNET_buffer_write_fstr (&buf,
    405                               ":%u",
    406                               (unsigned int) uri.port);
    407   if (NULL != uri.path)
    408     GNUNET_buffer_write_path (&buf,
    409                               uri.path);
    410   GNUNET_buffer_write_path (&buf,
    411                             template_id);
    412   GNUNET_free (url);
    413   return GNUNET_buffer_reap_str (&buf);
    414 }
    415 
    416 
    417 /**
    418  * Render @a s as a complete, double-quoted JavaScript string literal.
    419  *
    420  * The paywall page carries its context in `const' declarations inside a
    421  * <script> element, and mustache's default escaping is the wrong
    422  * escaping there twice over: it escapes exactly '<', '>', '&' and '"'
    423  * (mustach-wrap.c), which leaves the apostrophe free to close a
    424  * single-quoted literal and let arbitrary JavaScript follow, and the
    425  * entity references it does produce are never decoded, because the HTML
    426  * parser does not decode them inside a raw-text element -- an '&' in the
    427  * merchant base URL reached the script as the literal text "&amp;".
    428  *
    429  * So the value is escaped for the context it actually lands in, and
    430  * interpolated with the unescaped {{{ }}} since it arrives complete with
    431  * its quotes.  '<', '>' and '&' are still escaped, as \\uXXXX rather
    432  * than as entities: without that a value containing "</script>" would
    433  * end the element regardless of how well the string literal itself is
    434  * quoted.
    435  *
    436  * @param s string to render, must be valid UTF-8
    437  * @return JavaScript literal including the surrounding quotes,
    438  *         to be freed by the caller
    439  */
    440 static char *
    441 js_string_literal (const char *s)
    442 {
    443   struct GNUNET_Buffer buf = { 0 };
    444 
    445   GNUNET_buffer_write_str (&buf,
    446                            "\"");
    447   for (const unsigned char *p = (const unsigned char *) s;
    448        '\0' != *p;
    449        p++)
    450   {
    451     switch (*p)
    452     {
    453     case '"':
    454       GNUNET_buffer_write_str (&buf,
    455                                "\\\"");
    456       break;
    457     case '\\':
    458       GNUNET_buffer_write_str (&buf,
    459                                "\\\\");
    460       break;
    461     default:
    462       if ( (*p < 0x20) ||
    463            (0x7F == *p) ||
    464            ('<' == *p) ||
    465            ('>' == *p) ||
    466            ('&' == *p) )
    467         GNUNET_buffer_write_fstr (&buf,
    468                                   "\\u%04x",
    469                                   (unsigned int) *p);
    470       else
    471         GNUNET_buffer_write_fstr (&buf,
    472                                   "%c",
    473                                   (char) *p);
    474       break;
    475     }
    476   }
    477   GNUNET_buffer_write_str (&buf,
    478                            "\"");
    479   return GNUNET_buffer_reap_str (&buf);
    480 }
    481 
    482 
    483 /**
    484  * Record the language of an installed `paywall.$LANG.must' template.
    485  *
    486  * The scan intentionally uses the same directory and filename grammar as
    487  * TALER_TEMPLATING_init().  Directory traversal order is stable across the
    488  * two consecutive scans, preserving the templating library's first-template
    489  * fallback when no language matches.
    490  *
    491  * @param cls unused
    492  * @param filename file found in the template directory
    493  * @return #GNUNET_OK to continue, #GNUNET_SYSERR on the language cap
    494  */
    495 static enum GNUNET_GenericReturnValue
    496 collect_paywall_language (void *cls,
    497                           const char *filename)
    498 {
    499   const char *base;
    500   const char *lang;
    501   const char *end;
    502 
    503   (void) cls;
    504   base = strrchr (filename,
    505                   '/');
    506   base = (NULL == base) ? filename : base + 1;
    507   if (0 != strncmp (base,
    508                     "paywall.",
    509                     strlen ("paywall.")))
    510     return GNUNET_OK;
    511   lang = base + strlen ("paywall.");
    512   end = strchr (lang,
    513                 '.');
    514   if ( (lang == end) ||
    515        (NULL == end) ||
    516        (0 != strcmp (end,
    517                      ".must")) )
    518     return GNUNET_OK;
    519   if (paywall_languages_length >= MAX_PAYWALL_LANGUAGES)
    520   {
    521     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    522                 "More than %u paywall languages are installed; refusing"
    523                 " startup because language selection and cache variation"
    524                 " would exceed the documented bound\n",
    525                 (unsigned int) MAX_PAYWALL_LANGUAGES);
    526     return GNUNET_SYSERR;
    527   }
    528   paywall_languages[paywall_languages_length++]
    529     = GNUNET_strndup (lang,
    530                       end - lang);
    531   return GNUNET_OK;
    532 }
    533 
    534 
    535 bool
    536 PAIVANA_HTTPD_init_template_languages (void)
    537 {
    538   char *dir;
    539   char *tdir;
    540   int ret;
    541 
    542   GNUNET_assert (0 == paywall_languages_length);
    543   dir = GNUNET_OS_installation_get_path (PAIVANA_project_data (),
    544                                          GNUNET_OS_IPK_DATADIR);
    545   GNUNET_asprintf (&tdir,
    546                    "%stemplates",
    547                    dir);
    548   GNUNET_free (dir);
    549   ret = GNUNET_DISK_directory_scan (tdir,
    550                                     &collect_paywall_language,
    551                                     NULL);
    552   if ( (0 > ret) ||
    553        (0 == paywall_languages_length) )
    554   {
    555     if (0 == paywall_languages_length)
    556       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    557                   "No paywall.$LANG.must template is installed in `%s'\n",
    558                   tdir);
    559     GNUNET_free (tdir);
    560     return false;
    561   }
    562   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    563               "%u paywall language%s installed in `%s'\n",
    564               paywall_languages_length,
    565               (1 == paywall_languages_length) ? "" : "s",
    566               tdir);
    567   GNUNET_free (tdir);
    568   return true;
    569 }
    570 
    571 
    572 /**
    573  * The `Content-Security-Policy' for the paywall page, built once from
    574  * #PH_merchant_base_url.  NULL until first needed.
    575  */
    576 static char *paywall_csp;
    577 
    578 
    579 /**
    580  * Return the `Content-Security-Policy' for the paywall page.
    581  *
    582  * The page is entirely self-contained -- every stylesheet, script and
    583  * image is inline -- so everything but the merchant backend it polls
    584  * can be denied outright.  That is the part worth having: with
    585  * `default-src' at 'none' and `connect-src' naming exactly two origins,
    586  * script that does run cannot reach an attacker's host to report what
    587  * it found, and `frame-ancestors' keeps the taler:// link from being
    588  * framed and clicked by proxy.
    589  *
    590  * `script-src' still has to permit inline script: the page carries three
    591  * inline <script> elements and one `onclick' attribute, and neither
    592  * hashes nor a nonce survive our response cache, which serves one
    593  * rendered body to every client for five minutes.  Removing
    594  * 'unsafe-inline' means moving that handler into paywall.js and hashing
    595  * each block after rendering; worth doing, but it is not what makes the
    596  * injection this policy backs up impossible -- js_string_literal() is.
    597  *
    598  * @return the policy, owned by this module, or NULL if the merchant
    599  *         base URL cannot be parsed
    600  */
    601 static const char *
    602 get_paywall_csp (void)
    603 {
    604   struct GNUNET_Buffer buf = { 0 };
    605   struct GNUNET_Uri uri;
    606   char *url;
    607 
    608   if (NULL != paywall_csp)
    609     return paywall_csp;
    610   url = GNUNET_strdup (PH_merchant_base_url);
    611   if ( (-1 == GNUNET_uri_parse (&uri,
    612                                 url)) ||
    613        (NULL == uri.scheme) ||
    614        (NULL == uri.host) )
    615   {
    616     /* Cannot name the backend, and a policy that omits it would break
    617        the polling the page exists to do.  Serve without one rather than
    618        with a broken one; the URL is checked at startup, so this is the
    619        unreachable arm. */
    620     GNUNET_break (0);
    621     GNUNET_free (url);
    622     return NULL;
    623   }
    624   GNUNET_buffer_write_str (&buf,
    625                            "default-src 'none'; "
    626                            "script-src 'unsafe-inline'; "
    627                            "style-src 'unsafe-inline'; "
    628                            /* no img-src: the QR code is an inline
    629                               <svg> element, which loads nothing */
    630                            "connect-src 'self' ");
    631   GNUNET_buffer_write_str (&buf,
    632                            uri.scheme);
    633   GNUNET_buffer_write_str (&buf,
    634                            "://");
    635   GNUNET_buffer_write_str (&buf,
    636                            uri.host);
    637   if (0 != uri.port)
    638     GNUNET_buffer_write_fstr (&buf,
    639                               ":%u",
    640                               (unsigned int) uri.port);
    641   GNUNET_buffer_write_str (&buf,
    642                            "; frame-ancestors 'none'"
    643                            "; base-uri 'none'"
    644                            "; form-action 'none'");
    645   GNUNET_free (url);
    646   paywall_csp = GNUNET_buffer_reap_str (&buf);
    647   return paywall_csp;
    648 }
    649 
    650 
    651 /**
    652  * Return the language component of the render cache key for @a conn.
    653  *
    654  * Reproduce TALER_TEMPLATING_build()'s language choice from the installed
    655  * language list.  The cache is therefore keyed by one of at most 32 actual
    656  * variants instead of by an unbounded client-controlled header string.
    657  *
    658  * @param conn connection to derive the key component for
    659  * @return the key component, or NULL if `Accept-Language' does not
    660  *         affect the rendered body
    661  */
    662 static const char *
    663 cache_key_language (struct MHD_Connection *conn)
    664 {
    665   const char *pattern;
    666   const char *best = NULL;
    667   double best_q = 0.0;
    668 
    669   GNUNET_assert (0 != paywall_languages_length);
    670   pattern = MHD_lookup_connection_value (conn,
    671                                          MHD_HEADER_KIND,
    672                                          MHD_HTTP_HEADER_ACCEPT_LANGUAGE);
    673   if (NULL == pattern)
    674     pattern = "en";
    675   for (unsigned int i = 0; i < paywall_languages_length; i++)
    676   {
    677     double q = TALER_pattern_matches (pattern,
    678                                       paywall_languages[i]);
    679 
    680     if (q <= best_q)
    681       continue;
    682     best_q = q;
    683     best = paywall_languages[i];
    684   }
    685   /* This is the same first-loaded fallback as lookup_template() in the
    686      templating library. */
    687   return (NULL != best) ? best : paywall_languages[0];
    688 }
    689 
    690 
    691 /**
    692  * Try to initialize the paywall response.
    693  *
    694  * @param conn connection to create the response for
    695  * @param t template to create the response for
    696  * @return MHD status code to return
    697  */
    698 static enum MHD_Result
    699 load_paywall (struct MHD_Connection *conn,
    700               struct Template *t)
    701 {
    702   struct MHD_Response *reply;
    703   const char *lang;
    704   bool deflate;
    705   unsigned int http_status = MHD_HTTP_PAYMENT_REQUIRED;
    706 
    707   lang = cache_key_language (conn);
    708   /* `Accept-Encoding' reaches the body through exactly this predicate
    709      (templating_api.c), so keying on its result rather than on the
    710      header text is not an approximation: it is the decision itself,
    711      and it has two outcomes instead of unboundedly many. */
    712   deflate = (TALER_MHD_CT_DEFLATE ==
    713              TALER_MHD_can_compress (conn,
    714                                      TALER_MHD_CT_DEFLATE));
    715   for (struct ResponseCacheEntry *pos = rce_head;
    716        NULL != pos;
    717        pos = pos->next)
    718   {
    719     if ( (t == pos->template) &&
    720          (eq (lang,
    721               pos->lang)) &&
    722          (deflate == pos->deflate) )
    723     {
    724       if (rce_head != pos)
    725       {
    726         /* Hit, move pos to head of DLL for proper LRU eviction */
    727         GNUNET_CONTAINER_DLL_remove (rce_head,
    728                                      rce_tail,
    729                                      pos);
    730         GNUNET_CONTAINER_DLL_insert (rce_head,
    731                                      rce_tail,
    732                                      pos);
    733       }
    734       return MHD_queue_response (conn,
    735                                  pos->http_status,
    736                                  pos->paywall);
    737     }
    738   }
    739 
    740   {
    741     enum GNUNET_GenericReturnValue ret;
    742     json_t *data;
    743     char *tid_js = js_string_literal (t->template_id);
    744     char *mb_js = js_string_literal (PH_merchant_base_url);
    745 
    746     data = GNUNET_JSON_PACK (
    747       GNUNET_JSON_pack_string (
    748         "template_id",
    749         t->template_id),
    750       /* The `_js' variants are complete JavaScript string literals,
    751          quotes included, for the <script> block; the plain ones are for
    752          the HTML body, where mustache's own escaping is correct. */
    753       GNUNET_JSON_pack_string (
    754         "template_id_js",
    755         tid_js),
    756       GNUNET_JSON_pack_string (
    757         "merchant_backend_js",
    758         mb_js),
    759       GNUNET_JSON_pack_allow_null (
    760         GNUNET_JSON_pack_string (
    761           "summary",
    762           t->summary)),
    763       GNUNET_JSON_pack_allow_null (
    764         GNUNET_JSON_pack_array_incref (
    765           "choices",
    766           t->choices)),
    767       GNUNET_JSON_pack_bool (
    768         "has_choices",
    769         1 < json_array_size (t->choices)),
    770       GNUNET_JSON_pack_allow_null (
    771         GNUNET_JSON_pack_object_incref (
    772           "default_choice",
    773           json_array_get (t->choices, 0))),
    774       GNUNET_JSON_pack_bool (
    775         "has_pickup_deadline",
    776         ! GNUNET_TIME_relative_is_forever (t->max_pickup_delay)),
    777       GNUNET_JSON_pack_uint64 (
    778         "max_pickup_delay",
    779         /* Note: 'forever' will result in a very large number
    780            here, that is intentional, it is equivalent and avoids
    781            a special case on the client-side. */
    782         t->max_pickup_delay.rel_value_us / 1000LLU / 1000LLU),
    783       GNUNET_JSON_pack_string (
    784         "merchant_backend",
    785         PH_merchant_base_url));
    786     GNUNET_free (tid_js);
    787     GNUNET_free (mb_js);
    788     ret = TALER_TEMPLATING_build (
    789       conn,
    790       &http_status,
    791       "paywall",
    792       NULL /* no instance */,
    793       NULL /* no Taler URI (needs dynamic paivana_id!) */,
    794       data,
    795       &reply);
    796     json_decref (data);
    797     if (GNUNET_NO == ret)
    798     {
    799       enum MHD_Result mret;
    800 
    801       /* taler_templating_lib.h: #GNUNET_NO means an *error reply* was
    802          built — typically because the paywall template is not
    803          installed where TALER_TEMPLATING_init() looked.  It is a live
    804          MHD_Response and it is ours: returning #MHD_YES without
    805          queuing it leaked it once per unauthenticated request and left
    806          the client waiting for a status line that never came. */
    807       GNUNET_break (0);
    808       mret = MHD_queue_response (conn,
    809                                  http_status,
    810                                  reply);
    811       MHD_destroy_response (reply);
    812       return mret;
    813     }
    814     if (GNUNET_OK != ret)
    815     {
    816       /* #GNUNET_SYSERR: no reply was built, so there is nothing to
    817          queue and nothing to free; MHD must close the connection. */
    818       GNUNET_break (0);
    819       return MHD_NO;
    820     }
    821   }
    822 
    823 
    824   GNUNET_break (MHD_YES ==
    825                 MHD_add_response_header (reply,
    826                                          MHD_HTTP_HEADER_CONTENT_TYPE,
    827                                          "text/html"));
    828   /* The paywall body depends on the negotiated language and on
    829      whether we deflated it for the client; tell intermediaries to
    830      key their cache entries on both. */
    831   GNUNET_break (MHD_YES ==
    832                 MHD_add_response_header (reply,
    833                                          MHD_HTTP_HEADER_VARY,
    834                                          MHD_HTTP_HEADER_ACCEPT_LANGUAGE ", "
    835                                          MHD_HTTP_HEADER_ACCEPT_ENCODING ", "
    836                                          "Cookie"));
    837   GNUNET_break (MHD_YES ==
    838                 MHD_add_response_header (reply,
    839                                          MHD_HTTP_HEADER_CACHE_CONTROL,
    840                                          "public, max-age=300"));
    841   {
    842     const char *csp = get_paywall_csp ();
    843 
    844     if (NULL != csp)
    845       GNUNET_break (MHD_YES ==
    846                     MHD_add_response_header (reply,
    847                                              MHD_HTTP_HEADER_CONTENT_SECURITY_POLICY,
    848                                              csp));
    849   }
    850   /* frame-ancestors covers this for anything current; X-Frame-Options
    851      is for the user agents that do not implement it. */
    852   GNUNET_break (MHD_YES ==
    853                 MHD_add_response_header (reply,
    854                                          MHD_HTTP_HEADER_X_FRAME_OPTIONS,
    855                                          "DENY"));
    856   GNUNET_break (MHD_YES ==
    857                 MHD_add_response_header (reply,
    858                                          MHD_HTTP_HEADER_X_CONTENT_TYPE_OPTIONS,
    859                                          "nosniff"));
    860   {
    861     char *uri;
    862 
    863     uri = make_taler_pay_template_uri (PH_merchant_base_url,
    864                                        t->template_id);
    865     if (NULL != uri)
    866     {
    867       GNUNET_break (MHD_YES ==
    868                     MHD_add_response_header (reply,
    869                                              "Paivana",
    870                                              uri));
    871       GNUNET_free (uri);
    872     }
    873   }
    874 
    875   {
    876     struct ResponseCacheEntry *rce;
    877 
    878     /* '>=', not '>': the insert below is what takes us to the cap, so
    879        testing '>' left the steady state one entry above it. */
    880     while (rce_length >= MAX_RESPONSE_CACHE_ENTRIES)
    881     {
    882       /* Evict the least recently used entry; the hit path above
    883          promotes to the head, so the tail is the coldest. */
    884       struct ResponseCacheEntry *old = rce_tail;
    885 
    886       GNUNET_CONTAINER_DLL_remove (rce_head,
    887                                    rce_tail,
    888                                    old);
    889       GNUNET_assert (rce_length > 0);
    890       rce_length--;
    891       MHD_destroy_response (old->paywall);
    892       GNUNET_free (old->lang);
    893       GNUNET_free (old);
    894     }
    895     rce = GNUNET_new (struct ResponseCacheEntry);
    896     rce->template = t;
    897     if (NULL != lang)
    898       rce->lang = GNUNET_strdup (lang);
    899     rce->deflate = deflate;
    900     rce->paywall = reply;
    901     rce->http_status = http_status;
    902     rce_length++;
    903     GNUNET_CONTAINER_DLL_insert (rce_head,
    904                                  rce_tail,
    905                                  rce);
    906     return MHD_queue_response (conn,
    907                                rce->http_status,
    908                                reply);
    909   }
    910 }
    911 
    912 
    913 /**
    914  * Parse template contract to (mostly) determine the
    915  * regex specifying which websites the template applies to.
    916  *
    917  * @param[in,out] t template to update
    918  * @param contract contract to parse
    919  * @return true on success, false on failure
    920  */
    921 static bool
    922 parse_template (struct Template *t,
    923                 const json_t *contract)
    924 {
    925   /* An absent website_regex means "every URL".  So does an empty one:
    926      it is what a merchant UI stores for a template that was never
    927      given a restriction, and anchoring it would yield "^()$", which
    928      matches only the empty string and therefore no URL at all -- a
    929      template that silently paywalls nothing. */
    930   const char *regex = NULL;
    931   const char *summary = NULL;
    932   const json_t *choices = NULL;
    933   struct GNUNET_JSON_Specification spec[] = {
    934     GNUNET_JSON_spec_mark_optional (
    935       GNUNET_JSON_spec_string ("website_regex",
    936                                &regex),
    937       NULL),
    938     GNUNET_JSON_spec_mark_optional (
    939       GNUNET_JSON_spec_string ("summary",
    940                                &summary),
    941       NULL),
    942     GNUNET_JSON_spec_array_const ("choices",
    943                                   &choices),
    944     GNUNET_JSON_spec_mark_optional (
    945       GNUNET_JSON_spec_relative_time ("max_pickup_duration",
    946                                       &t->max_pickup_delay),
    947       NULL),
    948     GNUNET_JSON_spec_end ()
    949   };
    950   const char *en;
    951 
    952   if (GNUNET_OK !=
    953       GNUNET_JSON_parse ((json_t *) contract,
    954                          spec,
    955                          &en,
    956                          NULL))
    957   {
    958     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    959                 "Invalid template %s at field %s\n",
    960                 t->template_id,
    961                 en);
    962     return false;
    963   }
    964   /* GNUNET_JSON_spec_array_const() only establishes that "choices" is
    965      an array; what is *in* it is whatever the backend sent.
    966      load_paywall() hands element 0 to
    967      GNUNET_JSON_pack_object_incref(), which aborts on anything that is
    968      not an object — and it does so from an unauthenticated GET of the
    969      paywall page, so a backend that disagrees with us about the schema
    970      would turn every visitor into a crash loop.  We cross a network
    971      trust boundary here and must not assert on what comes back. */
    972   {
    973     size_t idx;
    974     json_t *choice;
    975 
    976     json_array_foreach ((json_t *) choices, idx, choice)
    977     {
    978       if (json_is_object (choice))
    979         continue;
    980       GNUNET_break_op (0);
    981       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    982                   "Template %s has a non-object choice at index %u\n",
    983                   t->template_id,
    984                   (unsigned int) idx);
    985       return false;
    986     }
    987   }
    988   if ( (NULL != regex) &&
    989        ('\0' != regex[0]) )
    990   {
    991     char *anchored;
    992     regex_t bare;
    993     int rc;
    994 
    995     /* Compile the merchant's expression as it stands *before* wrapping
    996        it, and refuse the template if that fails.  Splicing into a
    997        group is not a syntactic no-op: "a)|(b" becomes "^(a)|(b)$",
    998        which is "^a" OR "b$" -- each anchored on one side only, so the
    999        anchoring below stops being the guarantee the manual states.
   1000        Every such breakout needs a parenthesis that only balances
   1001        against the ones we add, which is exactly what a bare regcomp()
   1002        rejects.  The merchant backend compiles the bare expression on
   1003        POST /private/templates for the same reason; this closes the gap
   1004        for a template that reached the database some other way.  Note
   1005        that no expression that compiles on its own changes meaning
   1006        here. */
   1007     rc = regcomp (&bare,
   1008                   regex,
   1009                   REG_NOSUB | REG_EXTENDED);
   1010     if (0 != rc)
   1011     {
   1012       GNUNET_break_op (0);
   1013       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1014                   "Invalid regex in template %s: %s\n",
   1015                   t->template_id,
   1016                   regex);
   1017       return false;
   1018     }
   1019     regfree (&bare);
   1020     /* Anchor the merchant's expression: regexec(3) is unanchored, so
   1021        an expression like "/premium/" would otherwise put a paywall on
   1022        every URL merely *containing* it.  Wrapping in a group keeps
   1023        alternations ("a|b") from binding the anchors to only the first
   1024        and last branch.  An expression that already anchors itself is
   1025        unaffected, as ^ and $ inside still match at string
   1026        start/end. */
   1027     GNUNET_asprintf (&anchored,
   1028                      "^(%s)$",
   1029                      regex);
   1030     rc = regcomp (&t->ex,
   1031                   anchored,
   1032                   REG_NOSUB | REG_EXTENDED);
   1033     GNUNET_free (anchored);
   1034     if (0 != rc)
   1035     {
   1036       GNUNET_break_op (0);
   1037       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1038                   "Invalid regex in template %s: %s\n",
   1039                   t->template_id,
   1040                   regex);
   1041       return false;
   1042     }
   1043     t->regex = GNUNET_strdup (regex);
   1044   }
   1045   if (NULL != summary)
   1046     t->summary = GNUNET_strdup (summary);
   1047   t->choices = json_incref ((json_t *) choices);
   1048   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1049               "Using payment template %s for `%s'\n",
   1050               t->template_id,
   1051               (NULL != t->regex) ? t->regex : "(all URLs)");
   1052   return true;
   1053 }
   1054 
   1055 
   1056 /**
   1057  * Is @a contract a template that is ours to serve?
   1058  *
   1059  * The merchant's `template_type' discriminator; the literals are
   1060  * TALER_MERCHANT_template_type_from_string(), which we would call if
   1061  * it did not live in a library paivana does not otherwise need.  Note
   1062  * that an absent `template_type' is `fixed-order' there, so it is not
   1063  * ours either.
   1064  *
   1065  * @param contract template contract from the backend
   1066  * @return true if this is a paivana template
   1067  */
   1068 static bool
   1069 is_paivana_template (const json_t *contract)
   1070 {
   1071   const json_t *tt;
   1072 
   1073   tt = json_object_get (contract,
   1074                         "template_type");
   1075   return ( (NULL != tt) &&
   1076            (json_is_string (tt)) &&
   1077            (0 == strcmp ("paivana",
   1078                          json_string_value (tt))) );
   1079 }
   1080 
   1081 
   1082 /**
   1083  * Remove @a t from the list of templates and free it.
   1084  *
   1085  * Only for a template we decided not to use before anything was parsed
   1086  * into it: @e gt must already be NULL and nothing but the ID
   1087  * allocated.
   1088  *
   1089  * @param[in] t template to drop
   1090  */
   1091 static void
   1092 drop_template (struct Template *t)
   1093 {
   1094   GNUNET_assert (NULL == t->gt);
   1095   GNUNET_CONTAINER_DLL_remove (t_head,
   1096                                t_tail,
   1097                                t);
   1098   GNUNET_free (t->template_id);
   1099   GNUNET_free (t);
   1100 }
   1101 
   1102 
   1103 static void start_template_fetches (void);
   1104 
   1105 
   1106 /** Compare template pointers by ID for qsort(). */
   1107 static int
   1108 compare_template_ids (const void *a,
   1109                       const void *b)
   1110 {
   1111   const struct Template *const *ta = a;
   1112   const struct Template *const *tb = b;
   1113 
   1114   return strcmp ((*ta)->template_id,
   1115                  (*tb)->template_id);
   1116 }
   1117 
   1118 
   1119 /**
   1120  * Sort the retained templates once, after collection and filtering.
   1121  *
   1122  * Where expressions overlap, list order chooses the quoted price.  Sorting by
   1123  * ID makes that decision deterministic.  Collecting into an array and using
   1124  * qsort() is O(T log T), unlike the previous sorted DLL insertion's O(T^2).
   1125  */
   1126 static void
   1127 sort_templates (void)
   1128 {
   1129   struct Template **templates;
   1130   unsigned int i = 0;
   1131 
   1132   if (2 > loaded_paivana_templates)
   1133     return;
   1134   templates = GNUNET_malloc (loaded_paivana_templates
   1135                              * sizeof (*templates));
   1136   for (struct Template *t = t_head; NULL != t; t = t->next)
   1137     templates[i++] = t;
   1138   GNUNET_assert (i == loaded_paivana_templates);
   1139   qsort (templates,
   1140          loaded_paivana_templates,
   1141          sizeof (*templates),
   1142          &compare_template_ids);
   1143   t_head = NULL;
   1144   t_tail = NULL;
   1145   for (i = 0; i < loaded_paivana_templates; i++)
   1146   {
   1147     templates[i]->next = NULL;
   1148     templates[i]->prev = NULL;
   1149     GNUNET_CONTAINER_DLL_insert_tail (t_head,
   1150                                       t_tail,
   1151                                       templates[i]);
   1152   }
   1153   GNUNET_free (templates);
   1154 }
   1155 
   1156 
   1157 /** Finish template startup once no detail request is queued or active. */
   1158 static void
   1159 finish_template_loading (void)
   1160 {
   1161   if ( (0 != pending_template_fetches) ||
   1162        (0 != active_template_fetches) )
   1163     return;
   1164   sort_templates ();
   1165   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1166               "%u Paivana template%s loaded, starting to serve requests\n",
   1167               loaded_paivana_templates,
   1168               (1 == loaded_paivana_templates) ? "" : "s");
   1169   templates_ready ();
   1170 }
   1171 
   1172 
   1173 /**
   1174  * Callback for a GET /private/templates/$TEMPLATE_ID request.
   1175  *
   1176  * @param t template the request was about
   1177  * @param tgr response details
   1178  */
   1179 static void
   1180 setup_template (
   1181   struct Template *t,
   1182   const struct TALER_MERCHANT_GetPrivateTemplateResponse *tgr)
   1183 {
   1184   GNUNET_assert (TLS_ACTIVE == t->load_state);
   1185   GNUNET_assert (active_template_fetches > 0);
   1186   active_template_fetches--;
   1187   t->gt = NULL;
   1188   t->load_state = TLS_DONE;
   1189   switch (tgr->hr.http_status)
   1190   {
   1191   case MHD_HTTP_OK:
   1192     {
   1193       const json_t *contract = tgr->details.ok.template_contract;
   1194       size_t contract_size;
   1195 
   1196       if (! is_paivana_template (contract))
   1197       {
   1198         /* A shared merchant serves other template types too; they count only
   1199            against the broad discovery bound and are discarded here. */
   1200         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1201                     "Ignoring template %s: not a paivana template\n",
   1202                     t->template_id);
   1203         drop_template (t);
   1204         break;
   1205       }
   1206       if (loaded_paivana_templates >= MAX_PAIVANA_TEMPLATES)
   1207       {
   1208         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1209                     "Merchant offers more than %u Paivana templates;"
   1210                     " refusing startup to bound regex work and retained"
   1211                     " contract memory\n",
   1212                     (unsigned int) MAX_PAIVANA_TEMPLATES);
   1213         PH_global_ret = EXIT_NOTCONFIGURED;
   1214         GNUNET_SCHEDULER_shutdown ();
   1215         return;
   1216       }
   1217       contract_size = json_dumpb (contract,
   1218                                   NULL,
   1219                                   0,
   1220                                   JSON_COMPACT);
   1221       if (contract_size > MAX_TEMPLATE_CONTRACT_SIZE)
   1222       {
   1223         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1224                     "Template %s has a %llu-byte contract, exceeding the"
   1225                     " %u-byte startup and retained-memory limit\n",
   1226                     t->template_id,
   1227                     (unsigned long long) contract_size,
   1228                     (unsigned int) MAX_TEMPLATE_CONTRACT_SIZE);
   1229         PH_global_ret = EXIT_NOTCONFIGURED;
   1230         GNUNET_SCHEDULER_shutdown ();
   1231         return;
   1232       }
   1233       if (! parse_template (t,
   1234                             contract))
   1235       {
   1236         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1237                     "Failed to parse template %s, refusing to start\n",
   1238                     t->template_id);
   1239         PH_global_ret = EXIT_FAILURE;
   1240         GNUNET_SCHEDULER_shutdown ();
   1241         return;
   1242       }
   1243       loaded_paivana_templates++;
   1244       break;
   1245     }
   1246   default:
   1247     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1248                 "Failed to load template %s from backend"
   1249                 " (HTTP status %u), refusing to start\n",
   1250                 t->template_id,
   1251                 tgr->hr.http_status);
   1252     PH_global_ret = EXIT_FAILURE;
   1253     GNUNET_SCHEDULER_shutdown ();
   1254     return;
   1255   }
   1256   start_template_fetches ();
   1257   finish_template_loading ();
   1258 }
   1259 
   1260 
   1261 /** Start waiting detail requests until the eight-request window is full. */
   1262 static void
   1263 start_template_fetches (void)
   1264 {
   1265   while ( (active_template_fetches < MAX_TEMPLATE_FETCHES) &&
   1266           (0 != pending_template_fetches) )
   1267   {
   1268     struct Template *t = next_template_fetch;
   1269     enum TALER_ErrorCode ec;
   1270 
   1271     GNUNET_assert (NULL != t);
   1272     next_template_fetch = t->next;
   1273     GNUNET_assert (TLS_WAITING == t->load_state);
   1274     t->gt = TALER_MERCHANT_get_private_template_create (
   1275       PH_merchant_ctx,
   1276       PH_merchant_internal_url,
   1277       t->template_id);
   1278     if (NULL == t->gt)
   1279     {
   1280       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1281                   "Could not allocate merchant request for template %s\n",
   1282                   t->template_id);
   1283       PH_global_ret = EXIT_FAILURE;
   1284       GNUNET_SCHEDULER_shutdown ();
   1285       return;
   1286     }
   1287     t->load_state = TLS_ACTIVE;
   1288     pending_template_fetches--;
   1289     active_template_fetches++;
   1290     ec = TALER_MERCHANT_get_private_template_start (t->gt,
   1291                                                     &setup_template,
   1292                                                     t);
   1293     if (TALER_EC_NONE != ec)
   1294     {
   1295       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1296                   "Could not start merchant request for template %s: %d\n",
   1297                   t->template_id,
   1298                   (int) ec);
   1299       TALER_MERCHANT_get_private_template_cancel (t->gt);
   1300       t->gt = NULL;
   1301       t->load_state = TLS_DONE;
   1302       active_template_fetches--;
   1303       PH_global_ret = EXIT_FAILURE;
   1304       GNUNET_SCHEDULER_shutdown ();
   1305       return;
   1306     }
   1307   }
   1308 }
   1309 
   1310 
   1311 /**
   1312  * Callback for a GET /private/templates request.
   1313  *
   1314  * @param cls unused
   1315  * @param tgr response details
   1316  */
   1317 static void
   1318 check_templates (
   1319   void *cls,
   1320   const struct TALER_MERCHANT_GetPrivateTemplatesResponse *tgr)
   1321 {
   1322   (void) cls;
   1323   gpt = NULL;
   1324   /* The merchant client library enforces the same 1024-entry ceiling before
   1325      filling details.ok.  Preserve Paivana's own operator-facing diagnosis by
   1326      recognizing that parse-failure shape in the raw reply; without it the
   1327      callback reports only status zero/error 10 and the configured bound is
   1328      invisible. */
   1329   if ( (0 == tgr->hr.http_status) &&
   1330        (NULL != tgr->hr.reply) )
   1331   {
   1332     const json_t *templates = json_object_get (tgr->hr.reply,
   1333                                                "templates");
   1334 
   1335     if ( json_is_array (templates) &&
   1336          (json_array_size (templates) > MAX_DISCOVERED_TEMPLATES) )
   1337     {
   1338       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1339                   "Merchant returned %llu template IDs, exceeding the"
   1340                   " %u-entry startup bound\n",
   1341                   (unsigned long long) json_array_size (templates),
   1342                   (unsigned int) MAX_DISCOVERED_TEMPLATES);
   1343       PH_global_ret = EXIT_NOTCONFIGURED;
   1344       GNUNET_SCHEDULER_shutdown ();
   1345       return;
   1346     }
   1347   }
   1348   switch (tgr->hr.http_status)
   1349   {
   1350   case MHD_HTTP_OK:
   1351     break;
   1352   case MHD_HTTP_UNAUTHORIZED:
   1353     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1354                 "Access to templates unauthorized: %s\n",
   1355                 TALER_ErrorCode_get_hint (tgr->hr.ec));
   1356     PH_global_ret = EXIT_FAILURE;
   1357     GNUNET_SCHEDULER_shutdown ();
   1358     return;
   1359   default:
   1360     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1361                 "Unexpected HTTP status code %u on GET /private/templates (%d)\n",
   1362                 tgr->hr.http_status,
   1363                 (int) tgr->hr.ec);
   1364     PH_global_ret = EXIT_FAILURE;
   1365     GNUNET_SCHEDULER_shutdown ();
   1366     return;
   1367   }
   1368   if (0 == tgr->details.ok.templates_length)
   1369   {
   1370     templates_ready ();
   1371     return;
   1372   }
   1373   if (tgr->details.ok.templates_length > MAX_DISCOVERED_TEMPLATES)
   1374   {
   1375     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1376                 "Merchant returned %u template IDs, exceeding the %u-entry"
   1377                 " startup bound\n",
   1378                 tgr->details.ok.templates_length,
   1379                 (unsigned int) MAX_DISCOVERED_TEMPLATES);
   1380     PH_global_ret = EXIT_NOTCONFIGURED;
   1381     GNUNET_SCHEDULER_shutdown ();
   1382     return;
   1383   }
   1384 
   1385   for (unsigned int i = 0; i<tgr->details.ok.templates_length; i++)
   1386   {
   1387     const struct TALER_MERCHANT_GetPrivateTemplatesTemplateEntry *te
   1388       = &tgr->details.ok.templates[i];
   1389     struct Template *t;
   1390 
   1391     t = GNUNET_new (struct Template);
   1392     t->template_id = GNUNET_strdup (te->template_id);
   1393     t->max_pickup_delay = GNUNET_TIME_UNIT_FOREVER_REL;
   1394     t->load_state = TLS_WAITING;
   1395     GNUNET_CONTAINER_DLL_insert_tail (t_head,
   1396                                       t_tail,
   1397                                       t);
   1398   }
   1399   pending_template_fetches = tgr->details.ok.templates_length;
   1400   next_template_fetch = t_head;
   1401   start_template_fetches ();
   1402 }
   1403 
   1404 
   1405 void
   1406 PAIVANA_HTTPD_load_templates ()
   1407 {
   1408   GNUNET_assert (NULL == load_timeout_task);
   1409   load_timeout_task
   1410     = GNUNET_SCHEDULER_add_delayed (TEMPLATE_LOAD_TIMEOUT,
   1411                                     &load_timeout,
   1412                                     NULL);
   1413   gpt = TALER_MERCHANT_get_private_templates_create (PH_merchant_ctx,
   1414                                                      PH_merchant_internal_url);
   1415   if (NULL == gpt)
   1416   {
   1417     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1418                 "Could not allocate merchant template-list request\n");
   1419     PH_global_ret = EXIT_FAILURE;
   1420     GNUNET_SCHEDULER_shutdown ();
   1421     return;
   1422   }
   1423   {
   1424     enum TALER_ErrorCode ec;
   1425 
   1426     ec = TALER_MERCHANT_get_private_templates_start (gpt,
   1427                                                      &check_templates,
   1428                                                      NULL);
   1429     if (TALER_EC_NONE != ec)
   1430     {
   1431       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1432                   "Could not start merchant template-list request: %d\n",
   1433                   (int) ec);
   1434       TALER_MERCHANT_get_private_templates_cancel (gpt);
   1435       gpt = NULL;
   1436       PH_global_ret = EXIT_FAILURE;
   1437       GNUNET_SCHEDULER_shutdown ();
   1438     }
   1439   }
   1440 }
   1441 
   1442 
   1443 enum GNUNET_GenericReturnValue
   1444 PAIVANA_HTTPD_search_templates (struct MHD_Connection *connection,
   1445                                 const char *website)
   1446 {
   1447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
   1448               "Searching templates for `%s'\n",
   1449               website);
   1450   if (PH_MAX_URL_LENGTH < strlen (website))
   1451   {
   1452     enum MHD_Result ret;
   1453 
   1454     /* Refuse rather than returning #GNUNET_SYSERR: that would mean
   1455        "no paywall applies" and hand the request to the upstream for
   1456        free. */
   1457     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
   1458                 "Refusing to match templates against %llu byte URL\n",
   1459                 (unsigned long long) strlen (website));
   1460     ret = TALER_MHD_reply_with_error (
   1461       connection,
   1462       MHD_HTTP_URI_TOO_LONG,
   1463       TALER_EC_GENERIC_URI_TOO_LONG,
   1464       NULL);
   1465     return (MHD_YES == ret) ? GNUNET_OK : GNUNET_NO;
   1466   }
   1467   for (struct Template *t = t_head; NULL != t; t = t->next)
   1468   {
   1469     struct MHD_Response *redirect;
   1470     enum MHD_Result ret;
   1471     struct GNUNET_Buffer buf = { 0 };
   1472     char *enc = NULL;
   1473     char *url;
   1474 
   1475     if (NULL != t->regex)
   1476     {
   1477       int rc;
   1478 
   1479       rc = regexec (&t->ex,
   1480                     website,
   1481                     0, NULL,
   1482                     0);
   1483       if (REG_NOMATCH == rc)
   1484       {
   1485         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
   1486                     "Request for %s did not match template %s\n",
   1487                     website,
   1488                     t->template_id);
   1489         continue;
   1490       }
   1491       if (0 != rc)
   1492       {
   1493         char errbuf[128];
   1494 
   1495         /* Not "did not match": regexec(3) also reports REG_ESPACE,
   1496            whose likelihood is a function of the merchant's pattern and
   1497            the client's URL.  Taking the `continue' would drop this
   1498            template from consideration, and if it were the last one the
   1499            caller reads #GNUNET_SYSERR as "no paywall applies" and
   1500            serves the page for free.  Fail closed instead. */
   1501         GNUNET_break (0);
   1502         (void) regerror (rc,
   1503                          &t->ex,
   1504                          errbuf,
   1505                          sizeof (errbuf));
   1506         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
   1507                     "Failed to match template %s against %s: %s\n",
   1508                     t->template_id,
   1509                     website,
   1510                     errbuf);
   1511         ret = TALER_MHD_reply_with_error (
   1512           connection,
   1513           MHD_HTTP_INTERNAL_SERVER_ERROR,
   1514           TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE,
   1515           errbuf);
   1516         return (MHD_YES == ret) ? GNUNET_OK : GNUNET_NO;
   1517       }
   1518     }
   1519 
   1520     if (! PAIVANA_HTTPD_get_base_url (connection,
   1521                                       &buf))
   1522     {
   1523       GNUNET_break (0);
   1524       GNUNET_buffer_clear (&buf);
   1525       ret = TALER_MHD_reply_with_error (
   1526         connection,
   1527         MHD_HTTP_BAD_REQUEST,
   1528         TALER_EC_GENERIC_HTTP_HEADERS_MALFORMED,
   1529         "Host or X-Forwarded-Host required");
   1530       return (MHD_YES == ret) ? GNUNET_OK : GNUNET_NO;
   1531     }
   1532     (void) GNUNET_STRINGS_base64url_encode (website,
   1533                                             strlen (website),
   1534                                             &enc);
   1535     GNUNET_buffer_write_str (&buf,
   1536                              "/.well-known/paivana/templates/");
   1537     GNUNET_buffer_write_str (&buf,
   1538                              t->template_id);
   1539     GNUNET_buffer_write_str (&buf,
   1540                              "#");
   1541     GNUNET_buffer_write_str (&buf,
   1542                              enc);
   1543     GNUNET_free (enc);
   1544     url = GNUNET_buffer_reap_str (&buf);
   1545     redirect = MHD_create_response_from_buffer_static (0,
   1546                                                        NULL);
   1547     GNUNET_assert (NULL != redirect);
   1548     GNUNET_break (MHD_YES ==
   1549                   MHD_add_response_header (redirect,
   1550                                            MHD_HTTP_HEADER_LOCATION,
   1551                                            url));
   1552     /* Both the Location and the fragment are built from the base URL,
   1553        which -- unless BASE_URL pins it -- comes out of the forwarding
   1554        headers.  A cache sitting between the terminating proxy and us
   1555        would otherwise serve one client's redirect to another virtual
   1556        host (RFC 9110 section 12.5.5). */
   1557     GNUNET_break (MHD_YES ==
   1558                   MHD_add_response_header (redirect,
   1559                                            MHD_HTTP_HEADER_VARY,
   1560                                            (NULL != PH_base_url)
   1561                                            ? "Cookie"
   1562                                            : "Cookie, "
   1563                                            MHD_HTTP_HEADER_FORWARDED ", "
   1564                                            PH_HEADER_X_FORWARDED_PROTO ", "
   1565                                            PH_HEADER_X_FORWARDED_HOST ", "
   1566                                            PH_HEADER_X_FORWARDED_PORT));
   1567     GNUNET_break (MHD_YES ==
   1568                   MHD_add_response_header (redirect,
   1569                                            MHD_HTTP_HEADER_CACHE_CONTROL,
   1570                                            "public, max-age=60"));
   1571     GNUNET_free (url);
   1572     ret = MHD_queue_response (connection,
   1573                               MHD_HTTP_FOUND,
   1574                               redirect);
   1575     MHD_destroy_response (redirect);
   1576     return (MHD_YES == ret) ? GNUNET_OK : GNUNET_NO;
   1577   }
   1578   return GNUNET_SYSERR;
   1579 }
   1580 
   1581 
   1582 /**
   1583  * Return the paywall page for the given @a template.
   1584  *
   1585  * @param connection request to search paywall response for
   1586  * @param template template to return paywall page for
   1587  * @return MHD status code
   1588  */
   1589 enum MHD_Result
   1590 PAIVANA_HTTPD_return_template (struct MHD_Connection *connection,
   1591                                const char *template)
   1592 {
   1593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
   1594               "Searching template `%s'\n",
   1595               template);
   1596   for (struct Template *t = t_head; NULL != t; t = t->next)
   1597   {
   1598     if (0 == strcmp (template,
   1599                      t->template_id))
   1600       return load_paywall (connection,
   1601                            t);
   1602   }
   1603   /* No GNUNET_break_op() here: the ID is whatever the client put in the
   1604      path, this runs before any payment, and a stale bookmark or a
   1605      crawler would otherwise write an ERROR-level "Assertion failed" per
   1606      request.  A 404 is the whole answer. */
   1607   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
   1608               "No template `%s', returning 404\n",
   1609               template);
   1610   return TALER_MHD_reply_with_error (connection,
   1611                                      MHD_HTTP_NOT_FOUND,
   1612                                      TALER_EC_PAIVANA_TEMPLATE_UNKNOWN,
   1613                                      template);
   1614 }
   1615 
   1616 
   1617 /**
   1618  * Unload all of the template state.
   1619  */
   1620 void
   1621 PAIVANA_HTTPD_unload_templates ()
   1622 {
   1623   if (NULL != load_timeout_task)
   1624   {
   1625     GNUNET_SCHEDULER_cancel (load_timeout_task);
   1626     load_timeout_task = NULL;
   1627   }
   1628   while (NULL != rce_head)
   1629   {
   1630     struct ResponseCacheEntry *rce = rce_head;
   1631 
   1632     GNUNET_assert (rce_length > 0);
   1633     rce_length--;
   1634     GNUNET_CONTAINER_DLL_remove (rce_head,
   1635                                  rce_tail,
   1636                                  rce);
   1637     MHD_destroy_response (rce->paywall);
   1638     GNUNET_free (rce->lang);
   1639     GNUNET_free (rce);
   1640   }
   1641   while (NULL != t_head)
   1642   {
   1643     struct Template *t = t_head;
   1644 
   1645     GNUNET_CONTAINER_DLL_remove (t_head,
   1646                                  t_tail,
   1647                                  t);
   1648     if (NULL != t->gt)
   1649       TALER_MERCHANT_get_private_template_cancel (t->gt);
   1650     if (NULL != t->regex)
   1651     {
   1652       regfree (&t->ex);
   1653       GNUNET_free (t->regex);
   1654     }
   1655     GNUNET_free (t->template_id);
   1656     GNUNET_free (t->summary);
   1657     json_decref (t->choices);
   1658     GNUNET_free (t);
   1659   }
   1660   for (unsigned int i = 0; i < paywall_languages_length; i++)
   1661     GNUNET_free (paywall_languages[i]);
   1662   paywall_languages_length = 0;
   1663   pending_template_fetches = 0;
   1664   active_template_fetches = 0;
   1665   loaded_paivana_templates = 0;
   1666   next_template_fetch = NULL;
   1667   if (NULL != gpt)
   1668   {
   1669     TALER_MERCHANT_get_private_templates_cancel (gpt);
   1670     gpt = NULL;
   1671   }
   1672   GNUNET_free (paywall_csp);
   1673 }