LCOV - code coverage report
Current view: top level - backend - taler-merchant-httpd.c (source / functions) Hit Total Coverage
Test: GNU Taler merchant coverage report Lines: 364 464 78.4 %
Date: 2021-08-30 06:54:17 Functions: 16 17 94.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :   This file is part of TALER
       3             :   (C) 2014-2021 Taler Systems SA
       4             : 
       5             :   TALER is free software; you can redistribute it and/or modify it under the
       6             :   terms of the GNU Affero General Public License as published by the Free Software
       7             :   Foundation; either version 3, or (at your option) any later version.
       8             : 
       9             :   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
      10             :   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
      11             :   A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
      12             : 
      13             :   You should have received a copy of the GNU General Public License along with
      14             :   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
      15             : */
      16             : /**
      17             :  * @file taler-merchant-httpd.c
      18             :  * @brief HTTP serving layer intended to perform crypto-work and
      19             :  * communication with the exchange
      20             :  * @author Marcello Stanisci
      21             :  * @author Christian Grothoff
      22             :  * @author Florian Dold
      23             :  */
      24             : #include "platform.h"
      25             : #include <taler/taler_dbevents.h>
      26             : #include <taler/taler_bank_service.h>
      27             : #include <taler/taler_mhd_lib.h>
      28             : #include <taler/taler_exchange_service.h>
      29             : #include "taler-merchant-httpd_auditors.h"
      30             : #include "taler-merchant-httpd_config.h"
      31             : #include "taler-merchant-httpd_exchanges.h"
      32             : #include "taler-merchant-httpd_get-orders-ID.h"
      33             : #include "taler-merchant-httpd_get-tips-ID.h"
      34             : #include "taler-merchant-httpd_mhd.h"
      35             : #include "taler-merchant-httpd_private-delete-instances-ID.h"
      36             : #include "taler-merchant-httpd_private-delete-products-ID.h"
      37             : #include "taler-merchant-httpd_private-delete-orders-ID.h"
      38             : #include "taler-merchant-httpd_private-delete-reserves-ID.h"
      39             : #include "taler-merchant-httpd_private-delete-transfers-ID.h"
      40             : #include "taler-merchant-httpd_private-get-instances.h"
      41             : #include "taler-merchant-httpd_private-get-instances-ID.h"
      42             : #include "taler-merchant-httpd_private-get-products.h"
      43             : #include "taler-merchant-httpd_private-get-products-ID.h"
      44             : #include "taler-merchant-httpd_private-get-orders.h"
      45             : #include "taler-merchant-httpd_private-get-orders-ID.h"
      46             : #include "taler-merchant-httpd_private-get-reserves.h"
      47             : #include "taler-merchant-httpd_private-get-reserves-ID.h"
      48             : #include "taler-merchant-httpd_private-get-tips-ID.h"
      49             : #include "taler-merchant-httpd_private-get-tips.h"
      50             : #include "taler-merchant-httpd_private-get-transfers.h"
      51             : #include "taler-merchant-httpd_private-patch-instances-ID.h"
      52             : #include "taler-merchant-httpd_private-patch-orders-ID-forget.h"
      53             : #include "taler-merchant-httpd_private-patch-products-ID.h"
      54             : #include "taler-merchant-httpd_private-post-instances.h"
      55             : #include "taler-merchant-httpd_private-post-instances-ID-auth.h"
      56             : #include "taler-merchant-httpd_private-post-orders.h"
      57             : #include "taler-merchant-httpd_private-post-orders-ID-refund.h"
      58             : #include "taler-merchant-httpd_private-post-products.h"
      59             : #include "taler-merchant-httpd_private-post-products-ID-lock.h"
      60             : #include "taler-merchant-httpd_private-post-reserves.h"
      61             : #include "taler-merchant-httpd_private-post-reserves-ID-authorize-tip.h"
      62             : #include "taler-merchant-httpd_private-post-transfers.h"
      63             : #include "taler-merchant-httpd_post-orders-ID-abort.h"
      64             : #include "taler-merchant-httpd_post-orders-ID-claim.h"
      65             : #include "taler-merchant-httpd_post-orders-ID-paid.h"
      66             : #include "taler-merchant-httpd_post-orders-ID-pay.h"
      67             : #include "taler-merchant-httpd_post-orders-ID-refund.h"
      68             : #include "taler-merchant-httpd_post-tips-ID-pickup.h"
      69             : #include "taler-merchant-httpd_reserves.h"
      70             : #include "taler-merchant-httpd_spa.h"
      71             : #include "taler-merchant-httpd_statics.h"
      72             : #include "taler-merchant-httpd_templating.h"
      73             : 
      74             : /**
      75             :  * Fixme: document.
      76             :  */
      77             : #define INSTANCE_STALENESS GNUNET_TIME_UNIT_MINUTES
      78             : 
      79             : /**
      80             :  * Backlog for listen operation on unix-domain sockets.
      81             :  */
      82             : #define UNIX_BACKLOG 500
      83             : 
      84             : /**
      85             :  * Default maximum upload size permitted.  Can be overridden
      86             :  * per handler.
      87             :  */
      88             : #define DEFAULT_MAX_UPLOAD_SIZE (16 * 1024)
      89             : 
      90             : /**
      91             :  * Which currency do we use?
      92             :  */
      93             : char *TMH_currency;
      94             : 
      95             : /**
      96             :  * Inform the auditor for all deposit confirmations (global option)
      97             :  */
      98             : int TMH_force_audit;
      99             : 
     100             : /**
     101             :  * Connection handle to the our database
     102             :  */
     103             : struct TALER_MERCHANTDB_Plugin *TMH_db;
     104             : 
     105             : /**
     106             :  * Event handler for instance settings changes.
     107             :  */
     108             : static struct GNUNET_DB_EventHandler *instance_eh;
     109             : 
     110             : /**
     111             :  * Hashmap pointing at merchant instances by 'id'. An 'id' is
     112             :  * just a string that identifies a merchant instance. When a frontend
     113             :  * needs to specify an instance to the backend, it does so by 'id'
     114             :  */
     115             : struct GNUNET_CONTAINER_MultiHashMap *TMH_by_id_map;
     116             : 
     117             : /**
     118             :  * How long do we need to keep information on paid contracts on file for tax
     119             :  * or other legal reasons?  Used to block deletions for younger transaction
     120             :  * data.
     121             :  */
     122             : struct GNUNET_TIME_Relative TMH_legal_expiration;
     123             : 
     124             : /**
     125             :  * The port we are running on
     126             :  */
     127             : static uint16_t port;
     128             : 
     129             : /**
     130             :  * Should a "Connection: close" header be added to each HTTP response?
     131             :  */
     132             : static int merchant_connection_close;
     133             : 
     134             : /**
     135             :  * Global return code
     136             :  */
     137             : static int result;
     138             : 
     139             : /**
     140             :  * Our configuration.
     141             :  */
     142             : static const struct GNUNET_CONFIGURATION_Handle *cfg;
     143             : 
     144             : /**
     145             :  * Initial authorization token.
     146             :  */
     147             : char *TMH_default_auth;
     148             : 
     149             : 
     150             : int
     151         191 : TMH_check_auth (const char *token,
     152             :                 const struct GNUNET_ShortHashCode *salt,
     153             :                 const struct GNUNET_HashCode *hash)
     154             : {
     155             :   struct GNUNET_HashCode val;
     156             : 
     157         191 :   if (GNUNET_is_zero (hash))
     158         168 :     return GNUNET_OK;
     159          23 :   if (NULL == token)
     160           4 :     return GNUNET_SYSERR;
     161          19 :   GNUNET_assert (GNUNET_YES ==
     162             :                  GNUNET_CRYPTO_kdf (&val,
     163             :                                     sizeof (val),
     164             :                                     salt,
     165             :                                     sizeof (*salt),
     166             :                                     token,
     167             :                                     strlen (token),
     168             :                                     "merchant-instance-auth",
     169             :                                     strlen ("merchant-instance-auth"),
     170             :                                     NULL,
     171             :                                     0));
     172          19 :   return (0 == GNUNET_memcmp (&val,
     173             :                               hash))
     174             :     ? GNUNET_OK
     175          19 :     : GNUNET_SYSERR;
     176             : }
     177             : 
     178             : 
     179             : void
     180           7 : TMH_compute_auth (const char *token,
     181             :                   struct GNUNET_ShortHashCode *salt,
     182             :                   struct GNUNET_HashCode *hash)
     183             : {
     184           7 :   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
     185             :                               salt,
     186             :                               sizeof (*salt));
     187           7 :   GNUNET_assert (GNUNET_YES ==
     188             :                  GNUNET_CRYPTO_kdf (hash,
     189             :                                     sizeof (*hash),
     190             :                                     salt,
     191             :                                     sizeof (*salt),
     192             :                                     token,
     193             :                                     strlen (token),
     194             :                                     "merchant-instance-auth",
     195             :                                     strlen ("merchant-instance-auth"),
     196             :                                     NULL,
     197             :                                     0));
     198           7 : }
     199             : 
     200             : 
     201             : /**
     202             :  * Decrement reference counter of @a mi, and free if it hits zero.
     203             :  *
     204             :  * @param[in,out] mi merchant instance to update and possibly free
     205             :  */
     206             : static void
     207         386 : instance_decref (struct TMH_MerchantInstance *mi)
     208             : {
     209             :   struct TMH_WireMethod *wm;
     210             : 
     211         386 :   mi->rc--;
     212         386 :   if (0 != mi->rc)
     213         324 :     return;
     214          62 :   TMH_force_get_orders_resume (mi);
     215         126 :   while (NULL != (wm = (mi->wm_head)))
     216             :   {
     217          64 :     GNUNET_CONTAINER_DLL_remove (mi->wm_head,
     218             :                                  mi->wm_tail,
     219             :                                  wm);
     220          64 :     json_decref (wm->j_wire);
     221          64 :     GNUNET_free (wm->wire_method);
     222          64 :     GNUNET_free (wm);
     223             :   }
     224             : 
     225          62 :   GNUNET_free (mi->settings.id);
     226          62 :   GNUNET_free (mi->settings.name);
     227          62 :   json_decref (mi->settings.address);
     228          62 :   json_decref (mi->settings.jurisdiction);
     229          62 :   GNUNET_free (mi);
     230             : }
     231             : 
     232             : 
     233             : /**
     234             :  * Callback that frees an instances removing
     235             :  * it from the global hashmap.
     236             :  *
     237             :  * @param cls closure, NULL
     238             :  * @param key current key
     239             :  * @param value a `struct TMH_MerchantInstance`
     240             :  */
     241             : int
     242          62 : TMH_instance_free_cb (void *cls,
     243             :                       const struct GNUNET_HashCode *key,
     244             :                       void *value)
     245             : {
     246          62 :   struct TMH_MerchantInstance *mi = value;
     247             : 
     248             :   (void) cls;
     249             :   (void) key;
     250          62 :   GNUNET_assert (GNUNET_OK ==
     251             :                  GNUNET_CONTAINER_multihashmap_remove (TMH_by_id_map,
     252             :                                                        &mi->h_instance,
     253             :                                                        mi));
     254          62 :   instance_decref (mi);
     255          62 :   return GNUNET_YES;
     256             : }
     257             : 
     258             : 
     259             : /**
     260             :  * Shutdown task (magically invoked when the application is being
     261             :  * quit)
     262             :  *
     263             :  * @param cls NULL
     264             :  */
     265             : static void
     266          16 : do_shutdown (void *cls)
     267             : {
     268             :   (void) cls;
     269          16 :   TMH_force_ac_resume ();
     270          16 :   TMH_force_pc_resume ();
     271          16 :   TMH_force_rc_resume ();
     272          16 :   TMH_force_post_transfers_resume ();
     273          16 :   TMH_force_tip_pickup_resume ();
     274          16 :   TMH_force_wallet_get_order_resume ();
     275          16 :   TMH_force_wallet_refund_order_resume ();
     276             :   {
     277             :     struct MHD_Daemon *mhd;
     278             : 
     279          16 :     mhd = TALER_MHD_daemon_stop ();
     280          16 :     if (NULL != mhd)
     281          16 :       MHD_stop_daemon (mhd);
     282             :   }
     283          16 :   TMH_RESERVES_done ();
     284          16 :   if (NULL != instance_eh)
     285             :   {
     286          16 :     TMH_db->event_listen_cancel (instance_eh);
     287          16 :     instance_eh = NULL;
     288             :   }
     289          16 :   if (NULL != TMH_db)
     290             :   {
     291          16 :     TALER_MERCHANTDB_plugin_unload (TMH_db);
     292          16 :     TMH_db = NULL;
     293             :   }
     294          16 :   TMH_EXCHANGES_done ();
     295          16 :   TMH_AUDITORS_done ();
     296          16 :   if (NULL != TMH_by_id_map)
     297             :   {
     298          16 :     GNUNET_CONTAINER_multihashmap_iterate (TMH_by_id_map,
     299             :                                            &TMH_instance_free_cb,
     300             :                                            NULL);
     301          16 :     GNUNET_CONTAINER_multihashmap_destroy (TMH_by_id_map);
     302          16 :     TMH_by_id_map = NULL;
     303             :   }
     304          16 : }
     305             : 
     306             : 
     307             : /**
     308             :  * Function called whenever MHD is done with a request.  If the
     309             :  * request was a POST, we may have stored a `struct Buffer *` in the
     310             :  * @a con_cls that might still need to be cleaned up.  Call the
     311             :  * respective function to free the memory.
     312             :  *
     313             :  * @param cls client-defined closure
     314             :  * @param connection connection handle
     315             :  * @param con_cls value as set by the last call to
     316             :  *        the #MHD_AccessHandlerCallback
     317             :  * @param toe reason for request termination
     318             :  * @see #MHD_OPTION_NOTIFY_COMPLETED
     319             :  * @ingroup request
     320             :  */
     321             : static void
     322         362 : handle_mhd_completion_callback (void *cls,
     323             :                                 struct MHD_Connection *connection,
     324             :                                 void **con_cls,
     325             :                                 enum MHD_RequestTerminationCode toe)
     326             : {
     327         362 :   struct TMH_HandlerContext *hc = *con_cls;
     328             : 
     329         362 :   if (NULL == hc)
     330           0 :     return;
     331         362 :   GNUNET_SCHEDULER_begin_async_scope (&hc->async_scope_id);
     332             :   {
     333             : #if MHD_VERSION >= 0x00097304
     334             :     const union MHD_ConnectionInfo *ci;
     335         362 :     unsigned int http_status = 0;
     336             : 
     337         362 :     ci = MHD_get_connection_info (connection,
     338             :                                   MHD_CONNECTION_INFO_HTTP_STATUS);
     339         362 :     if (NULL != ci)
     340         362 :       http_status = ci->http_status;
     341         362 :     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
     342             :                 "Request for `%s' completed with HTTP status %u (%d)\n",
     343             :                 hc->url,
     344             :                 http_status,
     345             :                 toe);
     346             : #else
     347             :     (void) connection;
     348             :     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
     349             :                 "Finished handling request for `%s' with MHD termination code %d\n",
     350             :                 hc->url,
     351             :                 (int) toe);
     352             : #endif
     353             :   }
     354         362 :   if (NULL != hc->cc)
     355         130 :     hc->cc (hc->ctx);
     356         362 :   TALER_MHD_parse_post_cleanup_callback (hc->json_parse_context);
     357         362 :   GNUNET_free (hc->infix);
     358         362 :   if (NULL != hc->request_body)
     359         174 :     json_decref (hc->request_body);
     360         362 :   if (NULL != hc->instance)
     361         324 :     instance_decref (hc->instance);
     362         362 :   GNUNET_free (hc);
     363         362 :   *con_cls = NULL;
     364             : }
     365             : 
     366             : 
     367             : struct TMH_MerchantInstance *
     368         483 : TMH_lookup_instance (const char *instance_id)
     369             : {
     370             :   struct GNUNET_HashCode h_instance;
     371             : 
     372         483 :   if (NULL == instance_id)
     373         332 :     instance_id = "default";
     374         483 :   GNUNET_CRYPTO_hash (instance_id,
     375             :                       strlen (instance_id),
     376             :                       &h_instance);
     377         483 :   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
     378             :               "Looking for by-id key %s of '%s' in hashmap\n",
     379             :               GNUNET_h2s (&h_instance),
     380             :               instance_id);
     381             :   /* We're fine if that returns NULL, the calling routine knows how
     382             :      to handle that */
     383         483 :   return GNUNET_CONTAINER_multihashmap_get (TMH_by_id_map,
     384             :                                             &h_instance);
     385             : }
     386             : 
     387             : 
     388             : /**
     389             :  * Add instance definition to our active set of instances.
     390             :  *
     391             :  * @param[in,out] mi merchant instance details to define
     392             :  * @return #GNUNET_OK on success, #GNUNET_NO if the same ID is in use already
     393             :  */
     394             : int
     395          62 : TMH_add_instance (struct TMH_MerchantInstance *mi)
     396             : {
     397             :   const char *id;
     398             :   int ret;
     399             : 
     400          62 :   id = mi->settings.id;
     401          62 :   if (NULL == id)
     402           0 :     id = "default";
     403          62 :   GNUNET_CRYPTO_hash (id,
     404             :                       strlen (id),
     405             :                       &mi->h_instance);
     406          62 :   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
     407             :               "Looking for by-id key %s of `%s' in hashmap\n",
     408             :               GNUNET_h2s (&mi->h_instance),
     409             :               id);
     410          62 :   ret = GNUNET_CONTAINER_multihashmap_put (TMH_by_id_map,
     411          62 :                                            &mi->h_instance,
     412             :                                            mi,
     413             :                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
     414          62 :   if (GNUNET_OK == ret)
     415             :   {
     416          62 :     GNUNET_assert (mi->rc < UINT_MAX);
     417          62 :     mi->rc++;
     418             :   }
     419          62 :   return ret;
     420             : }
     421             : 
     422             : 
     423             : /**
     424             :  * Handle a OPTIONS "*" request.
     425             :  *
     426             :  * @param rh context of the handler
     427             :  * @param connection the MHD connection to handle
     428             :  * @param[in,out] hc context with further information about the request
     429             :  * @return MHD result code
     430             :  */
     431             : static MHD_RESULT
     432           0 : handle_server_options (const struct TMH_RequestHandler *rh,
     433             :                        struct MHD_Connection *connection,
     434             :                        struct TMH_HandlerContext *hc)
     435             : {
     436           0 :   return TALER_MHD_reply_cors_preflight (connection);
     437             : }
     438             : 
     439             : 
     440             : /**
     441             :  * Extract the token from authorization header value @a auth.
     442             :  *
     443             :  * @param auth pointer to authorization header value,
     444             :  *        will be updated to point to the start of the token
     445             :  *        or set to NULL if header value is invalid
     446             :  */
     447             : static void
     448          18 : extract_token (const char **auth)
     449             : {
     450          18 :   const char *bearer = "Bearer ";
     451          18 :   const char *tok = *auth;
     452             : 
     453          18 :   if (0 != strncmp (tok, bearer, strlen (bearer)))
     454             :   {
     455           1 :     *auth = NULL;
     456           1 :     return;
     457             :   }
     458          17 :   tok = tok + strlen (bearer);
     459          21 :   while (' ' == *tok)
     460           4 :     tok++;
     461          17 :   if (0 != strncasecmp (tok,
     462             :                         RFC_8959_PREFIX,
     463             :                         strlen (RFC_8959_PREFIX)))
     464             :   {
     465           0 :     *auth = NULL;
     466           0 :     return;
     467             :   }
     468          17 :   *auth = tok;
     469             : }
     470             : 
     471             : 
     472             : /**
     473             :  * Checks if the @a rh matches the given (parsed) URL.
     474             :  *
     475             :  * @param rh handler to compare against
     476             :  * @param url the main URL (without "/private/" prefix, if any)
     477             :  * @param prefix_strlen length of the prefix, i.e. 8 for '/orders/' or 7 for '/config'
     478             :  * @param infix_url infix text, i.e. "$ORDER_ID".
     479             :  * @param infix_strlen length of the string in @a infix_url
     480             :  * @param suffix_url suffix, i.e. "/refund", including the "/"
     481             :  * @param suffix_strlen number of characters in @a suffix_url
     482             :  * @return true if @a rh matches this request
     483             :  */
     484             : static bool
     485        3168 : prefix_match (const struct TMH_RequestHandler *rh,
     486             :               const char *url,
     487             :               size_t prefix_strlen,
     488             :               const char *infix_url,
     489             :               size_t infix_strlen,
     490             :               const char *suffix_url,
     491             :               size_t suffix_strlen)
     492             : {
     493        3168 :   if ( (prefix_strlen != strlen (rh->url_prefix)) ||
     494         962 :        (0 != memcmp (url,
     495         962 :                      rh->url_prefix,
     496             :                      prefix_strlen)) )
     497        2301 :     return false;
     498         867 :   if (! rh->have_id_segment)
     499             :   {
     500             :     /* Require /$PREFIX/$SUFFIX or /$PREFIX */
     501         186 :     if (NULL != suffix_url)
     502           0 :       return false;       /* too many segments to match */
     503         186 :     if ( (NULL == infix_url)   /* either or */
     504         186 :          ^ (NULL == rh->url_suffix) )
     505           0 :       return false;       /* suffix existence mismatch */
     506             :     /* If /$PREFIX/$SUFFIX, check $SUFFIX matches */
     507         186 :     if ( (NULL != infix_url) &&
     508           0 :          ( (infix_strlen != strlen (rh->url_suffix)) ||
     509           0 :            (0 != memcmp (infix_url,
     510           0 :                          rh->url_suffix,
     511             :                          infix_strlen)) ) )
     512           0 :       return false;       /* cannot use infix as suffix: content mismatch */
     513             :   }
     514             :   else
     515             :   {
     516             :     /* Require /$PREFIX/$ID or /$PREFIX/$ID/$SUFFIX */
     517         681 :     if (NULL == infix_url)
     518           0 :       return false;       /* infix existence mismatch */
     519         681 :     if ( ( (NULL == suffix_url)
     520         681 :            ^ (NULL == rh->url_suffix) ) )
     521         336 :       return false;       /* suffix existence mismatch */
     522         345 :     if ( (NULL != suffix_url) &&
     523         186 :          ( (suffix_strlen != strlen (rh->url_suffix)) ||
     524         126 :            (0 != memcmp (suffix_url,
     525         126 :                          rh->url_suffix,
     526             :                          suffix_strlen)) ) )
     527          96 :       return false;       /* suffix content mismatch */
     528             :   }
     529         435 :   return true;
     530             : }
     531             : 
     532             : 
     533             : /**
     534             :  * A client has requested the given url using the given method
     535             :  * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT,
     536             :  * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc).  The callback
     537             :  * must call MHD callbacks to provide content to give back to the
     538             :  * client and return an HTTP status code (i.e. #MHD_HTTP_OK,
     539             :  * #MHD_HTTP_NOT_FOUND, etc.).
     540             :  *
     541             :  * @param cls argument given together with the function
     542             :  *        pointer when the handler was registered with MHD
     543             :  * @param connection the MHD connection to handle
     544             :  * @param url the requested url
     545             :  * @param method the HTTP method used (#MHD_HTTP_METHOD_GET,
     546             :  *        #MHD_HTTP_METHOD_PUT, etc.)
     547             :  * @param version the HTTP version string (i.e.
     548             :  *        #MHD_HTTP_VERSION_1_1)
     549             :  * @param upload_data the data being uploaded (excluding HEADERS,
     550             :  *        for a POST that fits into memory and that is encoded
     551             :  *        with a supported encoding, the POST data will NOT be
     552             :  *        given in upload_data and is instead available as
     553             :  *        part of #MHD_get_connection_values; very large POST
     554             :  *        data *will* be made available incrementally in
     555             :  *        @a upload_data)
     556             :  * @param upload_data_size set initially to the size of the
     557             :  *        @a upload_data provided; the method must update this
     558             :  *        value to the number of bytes NOT processed;
     559             :  * @param con_cls pointer that the callback can set to some
     560             :  *        address and that will be preserved by MHD for future
     561             :  *        calls for this request; since the access handler may
     562             :  *        be called many times (i.e., for a PUT/POST operation
     563             :  *        with plenty of upload data) this allows the application
     564             :  *        to easily associate some request-specific state.
     565             :  *        If necessary, this state can be cleaned up in the
     566             :  *        global #MHD_RequestCompletedCallback (which
     567             :  *        can be set with the #MHD_OPTION_NOTIFY_COMPLETED).
     568             :  *        Initially, `*con_cls` will be NULL.
     569             :  * @return #MHD_YES if the connection was handled successfully,
     570             :  *         #MHD_NO if the socket must be closed due to a serious
     571             :  *         error while handling the request
     572             :  */
     573             : static MHD_RESULT
     574         931 : url_handler (void *cls,
     575             :              struct MHD_Connection *connection,
     576             :              const char *url,
     577             :              const char *method,
     578             :              const char *version,
     579             :              const char *upload_data,
     580             :              size_t *upload_data_size,
     581             :              void **con_cls)
     582             : {
     583             :   static struct TMH_RequestHandler management_handlers[] = {
     584             :     /* GET /instances */
     585             :     {
     586             :       .url_prefix = "/instances",
     587             :       .method = MHD_HTTP_METHOD_GET,
     588             :       .skip_instance = true,
     589             :       .default_only = true,
     590             :       .handler = &TMH_private_get_instances
     591             :     },
     592             :     /* POST /instances */
     593             :     {
     594             :       .url_prefix = "/instances",
     595             :       .method = MHD_HTTP_METHOD_POST,
     596             :       .skip_instance = true,
     597             :       .default_only = true,
     598             :       .handler = &TMH_private_post_instances,
     599             :       /* allow instance data of up to 8 MB, that should be plenty;
     600             :          note that exceeding #GNUNET_MAX_MALLOC_CHECKED (40 MB)
     601             :          would require further changes to the allocation logic
     602             :          in the code... */
     603             :       .max_upload = 1024 * 1024 * 8
     604             :     },
     605             :     /* GET /instances/$ID/ */
     606             :     {
     607             :       .url_prefix = "/instances/",
     608             :       .method = MHD_HTTP_METHOD_GET,
     609             :       .skip_instance = true,
     610             :       .default_only = true,
     611             :       .have_id_segment = true,
     612             :       .handler = &TMH_private_get_instances_default_ID
     613             :     },
     614             :     /* DELETE /instances/$ID */
     615             :     {
     616             :       .url_prefix = "/instances/",
     617             :       .method = MHD_HTTP_METHOD_DELETE,
     618             :       .skip_instance = true,
     619             :       .default_only = true,
     620             :       .have_id_segment = true,
     621             :       .handler = &TMH_private_delete_instances_default_ID
     622             :     },
     623             :     /* PATCH /instances/$ID */
     624             :     {
     625             :       .url_prefix = "/instances/",
     626             :       .method = MHD_HTTP_METHOD_PATCH,
     627             :       .skip_instance = true,
     628             :       .default_only = true,
     629             :       .have_id_segment = true,
     630             :       .handler = &TMH_private_patch_instances_default_ID,
     631             :       /* allow instance data of up to 8 MB, that should be plenty;
     632             :          note that exceeding #GNUNET_MAX_MALLOC_CHECKED (40 MB)
     633             :          would require further changes to the allocation logic
     634             :          in the code... */
     635             :       .max_upload = 1024 * 1024 * 8
     636             :     },
     637             :     /* POST /auth: */
     638             :     {
     639             :       .url_prefix = "/instances/",
     640             :       .url_suffix = "auth",
     641             :       .method = MHD_HTTP_METHOD_POST,
     642             :       .skip_instance = true,
     643             :       .default_only = true,
     644             :       .have_id_segment = true,
     645             :       .handler = &TMH_private_post_instances_default_ID_auth,
     646             :       /* Body should be pretty small. */
     647             :       .max_upload = 1024 * 1024
     648             :     },
     649             :     {
     650             :       NULL
     651             :     }
     652             :   };
     653             : 
     654             :   static struct TMH_RequestHandler private_handlers[] = {
     655             :     /* GET /instances/$ID/: */
     656             :     {
     657             :       .url_prefix = "/",
     658             :       .method = MHD_HTTP_METHOD_GET,
     659             :       .handler = &TMH_private_get_instances_ID
     660             :     },
     661             :     /* DELETE /instances/$ID/: */
     662             :     {
     663             :       .url_prefix = "/",
     664             :       .method = MHD_HTTP_METHOD_DELETE,
     665             :       .allow_deleted_instance = true,
     666             :       .handler = &TMH_private_delete_instances_ID
     667             :     },
     668             :     /* PATCH /instances/$ID/: */
     669             :     {
     670             :       .url_prefix = "/",
     671             :       .method = MHD_HTTP_METHOD_PATCH,
     672             :       .handler = &TMH_private_patch_instances_ID,
     673             :       .allow_deleted_instance = true,
     674             :       /* allow instance data of up to 8 MB, that should be plenty;
     675             :          note that exceeding #GNUNET_MAX_MALLOC_CHECKED (40 MB)
     676             :          would require further changes to the allocation logic
     677             :          in the code... */
     678             :       .max_upload = 1024 * 1024 * 8
     679             :     },
     680             :     /* POST /auth: */
     681             :     {
     682             :       .url_prefix = "/auth",
     683             :       .method = MHD_HTTP_METHOD_POST,
     684             :       .handler = &TMH_private_post_instances_ID_auth,
     685             :       /* Body should be pretty small. */
     686             :       .max_upload = 1024 * 1024,
     687             :     },
     688             :     /* GET /products: */
     689             :     {
     690             :       .url_prefix = "/products",
     691             :       .method = MHD_HTTP_METHOD_GET,
     692             :       .handler = &TMH_private_get_products
     693             :     },
     694             :     /* POST /products: */
     695             :     {
     696             :       .url_prefix = "/products",
     697             :       .method = MHD_HTTP_METHOD_POST,
     698             :       .handler = &TMH_private_post_products,
     699             :       /* allow product data of up to 8 MB, that should be plenty;
     700             :          note that exceeding #GNUNET_MAX_MALLOC_CHECKED (40 MB)
     701             :          would require further changes to the allocation logic
     702             :          in the code... */
     703             :       .max_upload = 1024 * 1024 * 8
     704             :     },
     705             :     /* GET /products/$ID/: */
     706             :     {
     707             :       .url_prefix = "/products/",
     708             :       .method = MHD_HTTP_METHOD_GET,
     709             :       .have_id_segment = true,
     710             :       .allow_deleted_instance = true,
     711             :       .handler = &TMH_private_get_products_ID
     712             :     },
     713             :     /* DELETE /products/$ID/: */
     714             :     {
     715             :       .url_prefix = "/products/",
     716             :       .method = MHD_HTTP_METHOD_DELETE,
     717             :       .have_id_segment = true,
     718             :       .allow_deleted_instance = true,
     719             :       .handler = &TMH_private_delete_products_ID
     720             :     },
     721             :     /* PATCH /products/$ID/: */
     722             :     {
     723             :       .url_prefix = "/products/",
     724             :       .method = MHD_HTTP_METHOD_PATCH,
     725             :       .have_id_segment = true,
     726             :       .allow_deleted_instance = true,
     727             :       .handler = &TMH_private_patch_products_ID,
     728             :       /* allow product data of up to 8 MB, that should be plenty;
     729             :          note that exceeding #GNUNET_MAX_MALLOC_CHECKED (40 MB)
     730             :          would require further changes to the allocation logic
     731             :          in the code... */
     732             :       .max_upload = 1024 * 1024 * 8
     733             :     },
     734             :     /* POST /products/$ID/lock: */
     735             :     {
     736             :       .url_prefix = "/products/",
     737             :       .url_suffix = "lock",
     738             :       .method = MHD_HTTP_METHOD_POST,
     739             :       .have_id_segment = true,
     740             :       .handler = &TMH_private_post_products_ID_lock,
     741             :       /* the body should be pretty small, allow 1 MB of upload
     742             :          to set a conservative bound for sane wallets */
     743             :       .max_upload = 1024 * 1024
     744             :     },
     745             :     /* POST /orders: */
     746             :     {
     747             :       .url_prefix = "/orders",
     748             :       .method = MHD_HTTP_METHOD_POST,
     749             :       .handler = &TMH_private_post_orders,
     750             :       /* allow contracts of up to 8 MB, that should be plenty;
     751             :          note that exceeding #GNUNET_MAX_MALLOC_CHECKED (40 MB)
     752             :          would require further changes to the allocation logic
     753             :          in the code... */
     754             :       .max_upload = 1024 * 1024 * 8
     755             :     },
     756             :     /* GET /orders/$ID: */
     757             :     {
     758             :       .url_prefix = "/orders/",
     759             :       .method = MHD_HTTP_METHOD_GET,
     760             :       .have_id_segment = true,
     761             :       .allow_deleted_instance = true,
     762             :       .handler = &TMH_private_get_orders_ID
     763             :     },
     764             :     /* GET /orders: */
     765             :     {
     766             :       .url_prefix = "/orders",
     767             :       .method = MHD_HTTP_METHOD_GET,
     768             :       .allow_deleted_instance = true,
     769             :       .handler = &TMH_private_get_orders
     770             :     },
     771             :     /* POST /orders/$ID/refund: */
     772             :     {
     773             :       .url_prefix = "/orders/",
     774             :       .url_suffix = "refund",
     775             :       .method = MHD_HTTP_METHOD_POST,
     776             :       .have_id_segment = true,
     777             :       .handler = &TMH_private_post_orders_ID_refund,
     778             :       /* the body should be pretty small, allow 1 MB of upload
     779             :          to set a conservative bound for sane wallets */
     780             :       .max_upload = 1024 * 1024
     781             :     },
     782             :     /* PATCH /orders/$ID/forget: */
     783             :     {
     784             :       .url_prefix = "/orders/",
     785             :       .url_suffix = "forget",
     786             :       .method = MHD_HTTP_METHOD_PATCH,
     787             :       .have_id_segment = true,
     788             :       .allow_deleted_instance = true,
     789             :       .handler = &TMH_private_patch_orders_ID_forget,
     790             :       /* the body should be pretty small, allow 1 MB of upload
     791             :          to set a conservative bound for sane wallets */
     792             :       .max_upload = 1024 * 1024
     793             :     },
     794             :     /* DELETE /orders/$ID: */
     795             :     {
     796             :       .url_prefix = "/orders/",
     797             :       .method = MHD_HTTP_METHOD_DELETE,
     798             :       .have_id_segment = true,
     799             :       .allow_deleted_instance = true,
     800             :       .handler = &TMH_private_delete_orders_ID
     801             :     },
     802             :     /* POST /reserves: */
     803             :     {
     804             :       .url_prefix = "/reserves",
     805             :       .method = MHD_HTTP_METHOD_POST,
     806             :       .handler = &TMH_private_post_reserves,
     807             :       /* the body should be pretty small, allow 1 MB of upload
     808             :          to set a conservative bound for sane wallets */
     809             :       .max_upload = 1024 * 1024
     810             :     },
     811             :     /* DELETE /reserves/$ID: */
     812             :     {
     813             :       .url_prefix = "/reserves/",
     814             :       .have_id_segment = true,
     815             :       .allow_deleted_instance = true,
     816             :       .method = MHD_HTTP_METHOD_DELETE,
     817             :       .handler = &TMH_private_delete_reserves_ID
     818             :     },
     819             :     /* POST /reserves/$ID/authorize-tip: */
     820             :     {
     821             :       .url_prefix = "/reserves/",
     822             :       .url_suffix = "authorize-tip",
     823             :       .have_id_segment = true,
     824             :       .method = MHD_HTTP_METHOD_POST,
     825             :       .handler = &TMH_private_post_reserves_ID_authorize_tip,
     826             :       /* the body should be pretty small, allow 1 MB of upload
     827             :          to set a conservative bound for sane wallets */
     828             :       .max_upload = 1024 * 1024
     829             :     },
     830             :     /* POST /tips: */
     831             :     {
     832             :       .url_prefix = "/tips",
     833             :       .method = MHD_HTTP_METHOD_POST,
     834             :       .handler = &TMH_private_post_tips,
     835             :       /* the body should be pretty small, allow 1 MB of upload
     836             :          to set a conservative bound for sane wallets */
     837             :       .max_upload = 1024 * 1024
     838             :     },
     839             :     /* GET /tips: */
     840             :     {
     841             :       .url_prefix = "/tips",
     842             :       .allow_deleted_instance = true,
     843             :       .method = MHD_HTTP_METHOD_GET,
     844             :       .handler = &TMH_private_get_tips
     845             :     },
     846             :     /* GET /tips/$ID: */
     847             :     {
     848             :       .url_prefix = "/tips/",
     849             :       .method = MHD_HTTP_METHOD_GET,
     850             :       .allow_deleted_instance = true,
     851             :       .have_id_segment = true,
     852             :       .handler = &TMH_private_get_tips_ID
     853             :     },
     854             :     /* GET /reserves: */
     855             :     {
     856             :       .url_prefix = "/reserves",
     857             :       .allow_deleted_instance = true,
     858             :       .method = MHD_HTTP_METHOD_GET,
     859             :       .handler = &TMH_private_get_reserves
     860             :     },
     861             :     /* GET /reserves/$ID: */
     862             :     {
     863             :       .url_prefix = "/reserves/",
     864             :       .allow_deleted_instance = true,
     865             :       .have_id_segment = true,
     866             :       .method = MHD_HTTP_METHOD_GET,
     867             :       .handler = &TMH_private_get_reserves_ID
     868             :     },
     869             :     /* POST /transfers: */
     870             :     {
     871             :       .url_prefix = "/transfers",
     872             :       .method = MHD_HTTP_METHOD_POST,
     873             :       .allow_deleted_instance = true,
     874             :       .handler = &TMH_private_post_transfers,
     875             :       /* the body should be pretty small, allow 1 MB of upload
     876             :          to set a conservative bound for sane wallets */
     877             :       .max_upload = 1024 * 1024
     878             :     },
     879             :     /* DELETE /transfers/$ID: */
     880             :     {
     881             :       .url_prefix = "/transfers/",
     882             :       .method = MHD_HTTP_METHOD_DELETE,
     883             :       .allow_deleted_instance = true,
     884             :       .handler = &TMH_private_delete_transfers_ID,
     885             :       .have_id_segment = true,
     886             :       /* the body should be pretty small, allow 1 MB of upload
     887             :          to set a conservative bound for sane wallets */
     888             :       .max_upload = 1024 * 1024
     889             :     },
     890             :     /* GET /transfers: */
     891             :     {
     892             :       .url_prefix = "/transfers",
     893             :       .method = MHD_HTTP_METHOD_GET,
     894             :       .allow_deleted_instance = true,
     895             :       .handler = &TMH_private_get_transfers
     896             :     },
     897             :     {
     898             :       NULL
     899             :     }
     900             :   };
     901             :   static struct TMH_RequestHandler public_handlers[] = {
     902             :     {
     903             :       .url_prefix = "/",
     904             :       .method = MHD_HTTP_METHOD_GET,
     905             :       .mime_type = "text/html",
     906             :       .skip_instance = true,
     907             :       .handler = &TMH_return_spa,
     908             :       .response_code = MHD_HTTP_OK
     909             :     },
     910             :     {
     911             :       .url_prefix = "/agpl",
     912             :       .method = MHD_HTTP_METHOD_GET,
     913             :       .skip_instance = true,
     914             :       .handler = &TMH_MHD_handler_agpl_redirect
     915             :     },
     916             :     {
     917             :       .url_prefix = "/config",
     918             :       .method = MHD_HTTP_METHOD_GET,
     919             :       .skip_instance = true,
     920             :       .default_only = true,
     921             :       .handler = &MH_handler_config
     922             :     },
     923             :     /* Also serve the same /config per instance */
     924             :     {
     925             :       .url_prefix = "/config",
     926             :       .method = MHD_HTTP_METHOD_GET,
     927             :       .skip_instance = false,
     928             :       .allow_deleted_instance = true,
     929             :       .handler = &MH_handler_config
     930             :     },
     931             :     /* POST /orders/$ID/abort: */
     932             :     {
     933             :       .url_prefix = "/orders/",
     934             :       .have_id_segment = true,
     935             :       .url_suffix = "abort",
     936             :       .method = MHD_HTTP_METHOD_POST,
     937             :       .handler = &TMH_post_orders_ID_abort,
     938             :       /* wallet may give us many coins to sign, allow 1 MB of upload
     939             :          to set a conservative bound for sane wallets */
     940             :       .max_upload = 1024 * 1024
     941             :     },
     942             :     /* POST /orders/$ID/claim: */
     943             :     {
     944             :       .url_prefix = "/orders/",
     945             :       .have_id_segment = true,
     946             :       .url_suffix = "claim",
     947             :       .method = MHD_HTTP_METHOD_POST,
     948             :       .handler = &TMH_post_orders_ID_claim,
     949             :       /* the body should be pretty small, allow 1 MB of upload
     950             :          to set a conservative bound for sane wallets */
     951             :       .max_upload = 1024 * 1024
     952             :     },
     953             :     /* POST /orders/$ID/pay: */
     954             :     {
     955             :       .url_prefix = "/orders/",
     956             :       .have_id_segment = true,
     957             :       .url_suffix = "pay",
     958             :       .method = MHD_HTTP_METHOD_POST,
     959             :       .handler = &TMH_post_orders_ID_pay,
     960             :       /* wallet may give us many coins to sign, allow 1 MB of upload
     961             :          to set a conservative bound for sane wallets */
     962             :       .max_upload = 1024 * 1024
     963             :     },
     964             :     /* POST /orders/$ID/paid: */
     965             :     {
     966             :       .url_prefix = "/orders/",
     967             :       .have_id_segment = true,
     968             :       .allow_deleted_instance = true,
     969             :       .url_suffix = "paid",
     970             :       .method = MHD_HTTP_METHOD_POST,
     971             :       .handler = &TMH_post_orders_ID_paid,
     972             :       /* the body should be pretty small, allow 1 MB of upload
     973             :          to set a conservative bound for sane wallets */
     974             :       .max_upload = 1024 * 1024
     975             :     },
     976             :     /* POST /orders/$ID/refund: */
     977             :     {
     978             :       .url_prefix = "/orders/",
     979             :       .have_id_segment = true,
     980             :       .allow_deleted_instance = true,
     981             :       .url_suffix = "refund",
     982             :       .method = MHD_HTTP_METHOD_POST,
     983             :       .handler = &TMH_post_orders_ID_refund,
     984             :       /* the body should be pretty small, allow 1 MB of upload
     985             :          to set a conservative bound for sane wallets */
     986             :       .max_upload = 1024 * 1024
     987             :     },
     988             :     /* GET /orders/$ID: */
     989             :     {
     990             :       .url_prefix = "/orders/",
     991             :       .method = MHD_HTTP_METHOD_GET,
     992             :       .allow_deleted_instance = true,
     993             :       .have_id_segment = true,
     994             :       .handler = &TMH_get_orders_ID
     995             :     },
     996             :     /* GET /tips/$ID: */
     997             :     {
     998             :       .url_prefix = "/tips/",
     999             :       .method = MHD_HTTP_METHOD_GET,
    1000             :       .allow_deleted_instance = true,
    1001             :       .have_id_segment = true,
    1002             :       .handler = &TMH_get_tips_ID
    1003             :     },
    1004             :     /* POST /tips/$ID/pickup: */
    1005             :     {
    1006             :       .url_prefix = "/tips/",
    1007             :       .method = MHD_HTTP_METHOD_POST,
    1008             :       .have_id_segment = true,
    1009             :       .allow_deleted_instance = true,
    1010             :       .url_suffix = "pickup",
    1011             :       .handler = &TMH_post_tips_ID_pickup,
    1012             :       /* wallet may give us many coins to sign, allow 1 MB of upload
    1013             :          to set a conservative bound for sane wallets */
    1014             :       .max_upload = 1024 * 1024
    1015             :     },
    1016             :     /* GET /static/ *: */
    1017             :     {
    1018             :       .url_prefix = "/static/",
    1019             :       .method = MHD_HTTP_METHOD_GET,
    1020             :       .have_id_segment = true,
    1021             :       .handler = &TMH_return_static
    1022             :     },
    1023             :     {
    1024             :       .url_prefix = "*",
    1025             :       .method = MHD_HTTP_METHOD_OPTIONS,
    1026             :       .handler = &handle_server_options
    1027             :     },
    1028             :     {
    1029             :       NULL
    1030             :     }
    1031             :   };
    1032         931 :   struct TMH_HandlerContext *hc = *con_cls;
    1033             :   struct TMH_RequestHandler *handlers;
    1034         931 :   bool use_default = false;
    1035             : 
    1036             :   (void) cls;
    1037             :   (void) version;
    1038         931 :   if (NULL != hc)
    1039             :   {
    1040             :     /* MHD calls us again for a request, for first call
    1041             :        see 'else' case below */
    1042         569 :     GNUNET_assert (NULL != hc->rh);
    1043         569 :     GNUNET_SCHEDULER_begin_async_scope (&hc->async_scope_id);
    1044         569 :     if ( (hc->has_body) &&
    1045         389 :          (NULL == hc->request_body) )
    1046             :     {
    1047         348 :       size_t mul = hc->rh->max_upload;
    1048             :       enum GNUNET_GenericReturnValue res;
    1049             : 
    1050         348 :       if (0 == mul)
    1051           0 :         mul = DEFAULT_MAX_UPLOAD_SIZE;
    1052         348 :       if ( (hc->total_upload + *upload_data_size < hc->total_upload) ||
    1053         348 :            (hc->total_upload + *upload_data_size > mul) )
    1054             :       {
    1055             :         /* Client exceeds upload limit. Should _usually_ be checked earlier
    1056             :            when we look at the MHD_HTTP_HEADER_CONTENT_LENGTH, alas with
    1057             :            chunked encoding an uploader MAY have omitted this, and thus
    1058             :            not permitted us to check on time. In this case, we just close
    1059             :            the connection once it exceeds our limit (instead of waiting
    1060             :            for the upload to complete and then fail). This could theoretically
    1061             :            cause some clients to retry, alas broken or malicious clients
    1062             :            are likely to retry anyway, so little we can do about it, and
    1063             :            failing earlier seems the best option here.  */
    1064           0 :         GNUNET_break_op (0);
    1065           0 :         return MHD_NO;
    1066             :       }
    1067         348 :       hc->total_upload += *upload_data_size;
    1068         348 :       res = TALER_MHD_parse_post_json (connection,
    1069             :                                        &hc->json_parse_context,
    1070             :                                        upload_data,
    1071             :                                        upload_data_size,
    1072             :                                        &hc->request_body);
    1073         348 :       if (GNUNET_SYSERR == res)
    1074           0 :         return MHD_NO;
    1075             :       /* A error response was already generated */
    1076         348 :       if ( (GNUNET_NO == res) ||
    1077             :            /* or, need more data to accomplish parsing */
    1078         348 :            (NULL == hc->request_body) )
    1079         174 :         return MHD_YES; /* let MHD call us *again* */
    1080             :     }
    1081             :     /* Upload complete (if any), call handler to generate reply */
    1082         395 :     return hc->rh->handler (hc->rh,
    1083             :                             connection,
    1084             :                             hc);
    1085             :   }
    1086         362 :   hc = GNUNET_new (struct TMH_HandlerContext);
    1087         362 :   *con_cls = hc;
    1088         362 :   GNUNET_async_scope_fresh (&hc->async_scope_id);
    1089         362 :   GNUNET_SCHEDULER_begin_async_scope (&hc->async_scope_id);
    1090         362 :   hc->url = url;
    1091             :   {
    1092             :     const char *correlation_id;
    1093             : 
    1094         362 :     correlation_id = MHD_lookup_connection_value (connection,
    1095             :                                                   MHD_HEADER_KIND,
    1096             :                                                   "Taler-Correlation-Id");
    1097         362 :     if ( (NULL != correlation_id) &&
    1098             :          (GNUNET_YES !=
    1099           0 :           GNUNET_CURL_is_valid_scope_id (correlation_id)) )
    1100             :     {
    1101           0 :       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
    1102             :                   "Illegal incoming correlation ID\n");
    1103           0 :       correlation_id = NULL;
    1104             :     }
    1105         362 :     if (NULL != correlation_id)
    1106           0 :       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    1107             :                   "Handling request for (%s) URL '%s', correlation_id=%s\n",
    1108             :                   method,
    1109             :                   url,
    1110             :                   correlation_id);
    1111             :     else
    1112         362 :       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    1113             :                   "Handling request (%s) for URL '%s'\n",
    1114             :                   method,
    1115             :                   url);
    1116             :   }
    1117             : 
    1118         362 :   if (0 == strcasecmp (method,
    1119             :                        MHD_HTTP_METHOD_HEAD))
    1120           0 :     method = MHD_HTTP_METHOD_GET; /* MHD will deal with the rest */
    1121             : 
    1122             :   /* Find out the merchant backend instance for the request.
    1123             :    * If there is an instance, remove the instance specification
    1124             :    * from the beginning of the request URL. */
    1125             :   {
    1126         362 :     const char *instance_prefix = "/instances/";
    1127             : 
    1128         362 :     if (0 == strncmp (url,
    1129             :                       instance_prefix,
    1130             :                       strlen (instance_prefix)))
    1131             :     {
    1132             :       /* url starts with "/instances/" */
    1133          30 :       const char *istart = url + strlen (instance_prefix);
    1134          30 :       const char *slash = strchr (istart, '/');
    1135             :       char *instance_id;
    1136             : 
    1137          30 :       if (NULL == slash)
    1138           0 :         instance_id = GNUNET_strdup (istart);
    1139             :       else
    1140          30 :         instance_id = GNUNET_strndup (istart,
    1141             :                                       slash - istart);
    1142          30 :       hc->instance = TMH_lookup_instance (instance_id);
    1143          30 :       GNUNET_free (instance_id);
    1144          30 :       if (NULL == slash)
    1145           0 :         url = "";
    1146             :       else
    1147          30 :         url = slash;
    1148             :     }
    1149             :     else
    1150             :     {
    1151             :       /* use 'default' */
    1152         332 :       use_default = true;
    1153         332 :       hc->instance = TMH_lookup_instance (NULL);
    1154         332 :       if ( (NULL != TMH_default_auth) &&
    1155           0 :            (NULL != hc->instance) )
    1156             :       {
    1157             :         /* Override default instance access control */
    1158           0 :         TMH_compute_auth (TMH_default_auth,
    1159           0 :                           &hc->instance->auth.auth_salt,
    1160           0 :                           &hc->instance->auth.auth_hash);
    1161           0 :         GNUNET_free (TMH_default_auth);
    1162             :       }
    1163             :     }
    1164         362 :     if (NULL != hc->instance)
    1165             :     {
    1166         324 :       GNUNET_assert (hc->instance->rc < UINT_MAX);
    1167         324 :       hc->instance->rc++;
    1168             :     }
    1169             :   }
    1170             : 
    1171             :   {
    1172         362 :     const char *management_prefix = "/management/";
    1173         362 :     const char *private_prefix = "/private/";
    1174             : 
    1175         362 :     if ( (0 == strncmp (url,
    1176             :                         management_prefix,
    1177             :                         strlen (management_prefix))) )
    1178             :     {
    1179          55 :       handlers = management_handlers;
    1180          55 :       url += strlen (management_prefix) - 1;
    1181             :     }
    1182         307 :     else if ( (0 == strncmp (url,
    1183             :                              private_prefix,
    1184         161 :                              strlen (private_prefix))) ||
    1185         161 :               (0 == strcmp (url,
    1186             :                             "/private")) )
    1187             :     {
    1188         153 :       handlers = private_handlers;
    1189         153 :       url += strlen (private_prefix) - 1;
    1190             :     }
    1191             :     else
    1192             :     {
    1193         154 :       handlers = public_handlers;
    1194             :     }
    1195             :   }
    1196             : 
    1197         362 :   if (0 == strcmp (url,
    1198             :                    ""))
    1199           7 :     url = "/"; /* code below does not like empty string */
    1200             : 
    1201             :   {
    1202             :     /* Matching URL found, but maybe method doesn't match */
    1203             :     size_t prefix_strlen; /* i.e. 8 for "/orders/", or 7 for "/config" */
    1204         362 :     const char *infix_url = NULL; /* i.e. "$ORDER_ID", no '/'-es */
    1205         362 :     size_t infix_strlen = 0; /* number of characters in infix_url */
    1206         362 :     const char *suffix_url = NULL; /* i.e. "refund", excludes '/' at the beginning */
    1207         362 :     size_t suffix_strlen = 0; /* number of characters in suffix_url */
    1208             : 
    1209             :     /* parse the URL into the three different components */
    1210             :     {
    1211             :       const char *slash;
    1212             : 
    1213         362 :       slash = strchr (&url[1], '/');
    1214         362 :       if (NULL == slash)
    1215             :       {
    1216             :         /* the prefix was everything */
    1217         140 :         prefix_strlen = strlen (url);
    1218             :       }
    1219             :       else
    1220             :       {
    1221         222 :         prefix_strlen = slash - url + 1; /* includes both '/'-es if present! */
    1222         222 :         infix_url = slash + 1;
    1223         222 :         slash = strchr (&infix_url[1], '/');
    1224         222 :         if (NULL == slash)
    1225             :         {
    1226             :           /* the infix was the rest */
    1227         129 :           infix_strlen = strlen (infix_url);
    1228             :         }
    1229             :         else
    1230             :         {
    1231          93 :           infix_strlen = slash - infix_url; /* excludes both '/'-es */
    1232          93 :           suffix_url = slash + 1; /* skip the '/' */
    1233          93 :           suffix_strlen = strlen (suffix_url);
    1234             :         }
    1235         222 :         hc->infix = GNUNET_strndup (infix_url,
    1236             :                                     infix_strlen);
    1237             :       }
    1238             :     }
    1239             : 
    1240             :     /* find matching handler */
    1241             :     {
    1242         362 :       bool url_found = false;
    1243             : 
    1244        3179 :       for (unsigned int i = 0; NULL != handlers[i].url_prefix; i++)
    1245             :       {
    1246        3172 :         struct TMH_RequestHandler *rh = &handlers[i];
    1247             : 
    1248        3172 :         if (rh->default_only && (! use_default))
    1249           4 :           continue;
    1250        3168 :         if (! prefix_match (rh,
    1251             :                             url,
    1252             :                             prefix_strlen,
    1253             :                             infix_url,
    1254             :                             infix_strlen,
    1255             :                             suffix_url,
    1256             :                             suffix_strlen))
    1257        2733 :           continue;
    1258         435 :         url_found = true;
    1259         435 :         if (0 == strcasecmp (method,
    1260             :                              MHD_HTTP_METHOD_OPTIONS))
    1261             :         {
    1262           0 :           return TALER_MHD_reply_cors_preflight (connection);
    1263             :         }
    1264         435 :         if ( (rh->method != NULL) &&
    1265         435 :              (0 != strcasecmp (method,
    1266             :                                rh->method)) )
    1267          80 :           continue;
    1268         355 :         hc->rh = rh;
    1269         355 :         break;
    1270             :       }
    1271             :       /* Handle HTTP 405: METHOD NOT ALLOWED case */
    1272         362 :       if ( (NULL == hc->rh) &&
    1273             :            (url_found) )
    1274             :       {
    1275             :         struct MHD_Response *reply;
    1276             :         MHD_RESULT ret;
    1277           0 :         char *allowed = NULL;
    1278             : 
    1279           0 :         GNUNET_break_op (0);
    1280             :         /* compute 'Allowed:' header (required by HTTP spec for 405 replies) */
    1281           0 :         for (unsigned int i = 0; NULL != handlers[i].url_prefix; i++)
    1282             :         {
    1283           0 :           struct TMH_RequestHandler *rh = &handlers[i];
    1284             : 
    1285           0 :           if (rh->default_only && (! use_default))
    1286           0 :             continue;
    1287           0 :           if (! prefix_match (rh,
    1288             :                               url,
    1289             :                               prefix_strlen,
    1290             :                               infix_url,
    1291             :                               infix_strlen,
    1292             :                               suffix_url,
    1293             :                               suffix_strlen))
    1294           0 :             continue;
    1295           0 :           if (NULL == allowed)
    1296             :           {
    1297           0 :             allowed = GNUNET_strdup (rh->method);
    1298             :           }
    1299             :           else
    1300             :           {
    1301             :             char *tmp;
    1302             : 
    1303           0 :             GNUNET_asprintf (&tmp,
    1304             :                              "%s, %s",
    1305             :                              allowed,
    1306             :                              rh->method);
    1307           0 :             GNUNET_free (allowed);
    1308           0 :             allowed = tmp;
    1309             :           }
    1310           0 :           if (0 == strcasecmp (rh->method,
    1311             :                                MHD_HTTP_METHOD_GET))
    1312             :           {
    1313             :             char *tmp;
    1314             : 
    1315           0 :             GNUNET_asprintf (&tmp,
    1316             :                              "%s, %s",
    1317             :                              allowed,
    1318             :                              MHD_HTTP_METHOD_HEAD);
    1319           0 :             GNUNET_free (allowed);
    1320           0 :             allowed = tmp;
    1321             :           }
    1322             :         }
    1323           0 :         reply = TALER_MHD_make_error (TALER_EC_GENERIC_METHOD_INVALID,
    1324             :                                       method);
    1325           0 :         GNUNET_break (MHD_YES ==
    1326             :                       MHD_add_response_header (reply,
    1327             :                                                MHD_HTTP_HEADER_ALLOW,
    1328             :                                                allowed));
    1329           0 :         GNUNET_free (allowed);
    1330           0 :         ret = MHD_queue_response (connection,
    1331             :                                   MHD_HTTP_METHOD_NOT_ALLOWED,
    1332             :                                   reply);
    1333           0 :         MHD_destroy_response (reply);
    1334           0 :         return ret;
    1335             :       }
    1336         362 :       if (NULL == hc->rh)
    1337           7 :         return TALER_MHD_reply_with_error (connection,
    1338             :                                            MHD_HTTP_NOT_FOUND,
    1339             :                                            TALER_EC_GENERIC_ENDPOINT_UNKNOWN,
    1340             :                                            hc->url);
    1341             :     }
    1342             :   }
    1343             :   /* At this point, we must have found a handler */
    1344         355 :   GNUNET_assert (NULL != hc->rh);
    1345             : 
    1346             :   /* If an instance should be there, check one exists */
    1347         355 :   if ( (NULL == hc->instance) &&
    1348          37 :        (! hc->rh->skip_instance) )
    1349             :   {
    1350           2 :     return TALER_MHD_reply_with_error (connection,
    1351             :                                        MHD_HTTP_NOT_FOUND,
    1352             :                                        TALER_EC_MERCHANT_GENERIC_INSTANCE_UNKNOWN,
    1353           2 :                                        hc->infix);
    1354             :   }
    1355             : 
    1356             :   /* Access control for non-public handlers */
    1357         353 :   if (public_handlers != handlers)
    1358             :   {
    1359             :     const char *auth;
    1360             :     bool auth_ok;
    1361         201 :     bool auth_malformed = false;
    1362             : 
    1363             :     /* PATCHing an instance can alternatively be checked against
    1364             :        the default instance */
    1365         201 :     auth = MHD_lookup_connection_value (connection,
    1366             :                                         MHD_HEADER_KIND,
    1367             :                                         MHD_HTTP_HEADER_AUTHORIZATION);
    1368         201 :     if (NULL != auth)
    1369             :     {
    1370             :       /* We _only_ complain about malformed auth headers if
    1371             :          authorization was truly required (#6737). This helps
    1372             :          in case authorization was disabled in the backend
    1373             :          because some reverse proxy is already doing it, and
    1374             :          then that reverse proxy may forward malformed auth
    1375             :          headers to the backend. */
    1376          18 :       extract_token (&auth);
    1377          18 :       if (NULL == auth)
    1378           1 :         auth_malformed = true;
    1379          18 :       hc->auth_token = auth;
    1380             :     }
    1381             : 
    1382             :     /* If we have zero configured instances (not even ones that have been
    1383             :        purged) AND no override credentials, THEN we accept anything (no access
    1384             :        control), as we then also have no data to protect. */
    1385         201 :     auth_ok = ( (0 ==
    1386         217 :                  GNUNET_CONTAINER_multihashmap_size (TMH_by_id_map)) &&
    1387          16 :                 (NULL == TMH_default_auth) );
    1388             :     /* Check against selected instance, if we have one */
    1389         201 :     if (NULL != hc->instance)
    1390         185 :       auth_ok |= (GNUNET_OK ==
    1391         185 :                   TMH_check_auth (auth,
    1392         185 :                                   &hc->instance->auth.auth_salt,
    1393         185 :                                   &hc->instance->auth.auth_hash));
    1394             :     else /* Are the credentials provided OK for CLI override? */
    1395          16 :       auth_ok |= ( (use_default) &&
    1396          16 :                    (NULL != TMH_default_auth) &&
    1397           0 :                    (NULL != auth) &&
    1398          32 :                    (! auth_malformed) &&
    1399           0 :                    (0 == strcmp (auth,
    1400             :                                  TMH_default_auth)) );
    1401         201 :     if (! auth_ok)
    1402             :     {
    1403          10 :       if (auth_malformed)
    1404          10 :         return TALER_MHD_reply_with_error (connection,
    1405             :                                            MHD_HTTP_UNAUTHORIZED,
    1406             :                                            TALER_EC_GENERIC_PARAMETER_MALFORMED,
    1407             :                                            "'" RFC_8959_PREFIX
    1408             :                                            "' prefix or 'Bearer' missing in 'Authorization' header");
    1409          10 :       return TALER_MHD_reply_with_error (connection,
    1410             :                                          MHD_HTTP_UNAUTHORIZED,
    1411             :                                          TALER_EC_MERCHANT_GENERIC_UNAUTHORIZED,
    1412             :                                          "Check 'Authorization' header");
    1413             :     }
    1414             :   } /* if (use_private) */
    1415             : 
    1416             : 
    1417         343 :   if ( (NULL == hc->instance) &&
    1418          35 :        (! hc->rh->skip_instance) )
    1419           0 :     return TALER_MHD_reply_with_error (connection,
    1420             :                                        MHD_HTTP_NOT_FOUND,
    1421             :                                        TALER_EC_MERCHANT_GENERIC_INSTANCE_UNKNOWN,
    1422             :                                        url);
    1423         343 :   if ( (NULL != hc->instance) && /* make static analysis happy */
    1424         308 :        (! hc->rh->skip_instance) &&
    1425         270 :        (hc->instance->deleted) &&
    1426           1 :        (! hc->rh->allow_deleted_instance) )
    1427           1 :     return TALER_MHD_reply_with_error (connection,
    1428             :                                        MHD_HTTP_NOT_FOUND,
    1429             :                                        TALER_EC_MERCHANT_GENERIC_INSTANCE_DELETED,
    1430           1 :                                        hc->instance->settings.id);
    1431             :   /* parse request body */
    1432         684 :   hc->has_body = ( (0 == strcasecmp (method,
    1433         523 :                                      MHD_HTTP_METHOD_POST)) ||
    1434             :                    /* PUT is not yet used */
    1435         181 :                    (0 == strcasecmp (method,
    1436             :                                      MHD_HTTP_METHOD_PATCH)) );
    1437         342 :   if (hc->has_body)
    1438             :   {
    1439             :     const char *cl;
    1440             : 
    1441             :     /* Maybe check for maximum upload size
    1442             :        and refuse requests if they are just too big. */
    1443         174 :     cl = MHD_lookup_connection_value (connection,
    1444             :                                       MHD_HEADER_KIND,
    1445             :                                       MHD_HTTP_HEADER_CONTENT_LENGTH);
    1446         174 :     if (NULL != cl)
    1447             :     {
    1448             :       unsigned long long cv;
    1449         174 :       size_t mul = hc->rh->max_upload;
    1450             :       char dummy;
    1451             : 
    1452         174 :       if (0 == mul)
    1453           0 :         mul = DEFAULT_MAX_UPLOAD_SIZE;
    1454         174 :       if (1 != sscanf (cl,
    1455             :                        "%llu%c",
    1456             :                        &cv,
    1457             :                        &dummy))
    1458             :       {
    1459             :         /* Not valid HTTP request, just close connection. */
    1460           0 :         GNUNET_break_op (0);
    1461           0 :         return MHD_NO;
    1462             :       }
    1463         174 :       if (cv > mul)
    1464             :       {
    1465           0 :         GNUNET_break_op (0);
    1466           0 :         return TALER_MHD_reply_with_error (connection,
    1467             :                                            MHD_HTTP_PAYLOAD_TOO_LARGE,
    1468             :                                            TALER_EC_GENERIC_UPLOAD_EXCEEDS_LIMIT,
    1469             :                                            cl);
    1470             :       }
    1471             :     }
    1472         174 :     GNUNET_break (NULL == hc->request_body); /* can't have it already */
    1473             :   }
    1474         342 :   return MHD_YES; /* wait for MHD to call us again */
    1475             : }
    1476             : 
    1477             : 
    1478             : /**
    1479             :  * Function called during startup to add all known instances to our
    1480             :  * hash map in memory for faster lookups when we receive requests.
    1481             :  *
    1482             :  * @param cls closure, NULL, unused
    1483             :  * @param merchant_pub public key of the instance
    1484             :  * @param merchant_priv private key of the instance, NULL if not available
    1485             :  * @param is detailed configuration settings for the instance
    1486             :  * @param ias authentication settings for the instance
    1487             :  * @param accounts_length length of the @a accounts array
    1488             :  * @param accounts list of accounts of the merchant
    1489             :  */
    1490             : static void
    1491          36 : add_instance_cb (void *cls,
    1492             :                  const struct TALER_MerchantPublicKeyP *merchant_pub,
    1493             :                  const struct TALER_MerchantPrivateKeyP *merchant_priv,
    1494             :                  const struct TALER_MERCHANTDB_InstanceSettings *is,
    1495             :                  const struct TALER_MERCHANTDB_InstanceAuthSettings *ias,
    1496             :                  unsigned int accounts_length,
    1497             :                  const struct TALER_MERCHANTDB_AccountDetails accounts[])
    1498             : {
    1499             :   struct TMH_MerchantInstance *mi;
    1500             : 
    1501             :   (void) cls;
    1502          36 :   mi = TMH_lookup_instance (is->id);
    1503          36 :   if (NULL != mi)
    1504             :   {
    1505             :     /* (outdated) entry exists, remove old entry */
    1506           0 :     (void) TMH_instance_free_cb (NULL,
    1507           0 :                                  &mi->h_instance,
    1508             :                                  mi);
    1509             :   }
    1510             : 
    1511          36 :   mi = GNUNET_new (struct TMH_MerchantInstance);
    1512          36 :   mi->settings = *is;
    1513          36 :   mi->auth = *ias;
    1514          36 :   mi->settings.id = GNUNET_strdup (mi->settings.id);
    1515          36 :   mi->settings.name = GNUNET_strdup (mi->settings.name);
    1516          36 :   mi->settings.address = json_incref (mi->settings.address);
    1517          36 :   mi->settings.jurisdiction = json_incref (mi->settings.jurisdiction);
    1518          36 :   if (NULL != merchant_priv)
    1519          35 :     mi->merchant_priv = *merchant_priv;
    1520             :   else
    1521           1 :     mi->deleted = true;
    1522          36 :   mi->merchant_pub = *merchant_pub;
    1523          73 :   for (unsigned int i = 0; i<accounts_length; i++)
    1524             :   {
    1525          37 :     const struct TALER_MERCHANTDB_AccountDetails *acc = &accounts[i];
    1526             :     struct TMH_WireMethod *wm;
    1527             : 
    1528          37 :     wm = GNUNET_new (struct TMH_WireMethod);
    1529          37 :     wm->h_wire = acc->h_wire;
    1530          37 :     wm->j_wire = GNUNET_JSON_PACK (
    1531             :       GNUNET_JSON_pack_string ("payto_uri",
    1532             :                                acc->payto_uri),
    1533             :       GNUNET_JSON_pack_data_auto ("salt",
    1534             :                                   &acc->salt));
    1535          37 :     wm->wire_method = TALER_payto_get_method (acc->payto_uri);
    1536          37 :     wm->active = acc->active;
    1537          37 :     GNUNET_CONTAINER_DLL_insert (mi->wm_head,
    1538             :                                  mi->wm_tail,
    1539             :                                  wm);
    1540             :   }
    1541          36 :   GNUNET_assert (GNUNET_OK ==
    1542             :                  TMH_add_instance (mi));
    1543          36 : }
    1544             : 
    1545             : 
    1546             : /**
    1547             :  * Trigger (re)loading of instance settings from DB.
    1548             :  *
    1549             :  * @param cls NULL
    1550             :  * @param extra ID of the instance that changed, NULL
    1551             :  *              to load all instances (will not handle purges!)
    1552             :  * @param extra_len number of bytes in @a extra
    1553             :  */
    1554             : static void
    1555          58 : load_instances (void *cls,
    1556             :                 const void *extra,
    1557             :                 size_t extra_len)
    1558             : {
    1559             :   enum GNUNET_DB_QueryStatus qs;
    1560          58 :   const char *id = extra;
    1561             : 
    1562             :   (void) cls;
    1563             :   (void) extra;
    1564             :   (void) extra_len;
    1565          58 :   if ( (NULL != extra) &&
    1566          42 :        ( (0 == extra_len) ||
    1567          42 :          ('\0' != id[extra_len - 1]) ) )
    1568             :   {
    1569           0 :     GNUNET_break (0 == extra_len);
    1570           0 :     extra = NULL;
    1571             :   }
    1572          58 :   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    1573             :               "Received instance settings notification: reload `%s'\n",
    1574             :               id);
    1575          58 :   if (NULL == extra)
    1576             :   {
    1577          16 :     qs = TMH_db->lookup_instances (TMH_db->cls,
    1578             :                                    false,
    1579             :                                    &add_instance_cb,
    1580             :                                    NULL);
    1581             :   }
    1582             :   else
    1583             :   {
    1584             :     struct TMH_MerchantInstance *mi;
    1585             : 
    1586             :     /* This must be done here to handle instance
    1587             :        purging, as for purged instances, the DB
    1588             :        lookup below will otherwise do nothing */
    1589          42 :     mi = TMH_lookup_instance (id);
    1590          42 :     if (NULL != mi)
    1591             :     {
    1592          42 :       (void) TMH_instance_free_cb (NULL,
    1593          42 :                                    &mi->h_instance,
    1594             :                                    mi);
    1595             :     }
    1596          42 :     qs = TMH_db->lookup_instance (TMH_db->cls,
    1597             :                                   id,
    1598             :                                   false,
    1599             :                                   &add_instance_cb,
    1600             :                                   NULL);
    1601             :   }
    1602          58 :   if (0 > qs)
    1603             :   {
    1604           0 :     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    1605             :                 "Failed initialization. Check database setup.\n");
    1606           0 :     result = EXIT_FAILURE;
    1607           0 :     GNUNET_SCHEDULER_shutdown ();
    1608           0 :     return;
    1609             :   }
    1610             : }
    1611             : 
    1612             : 
    1613             : /**
    1614             :  * A transaction modified an instance setting
    1615             :  * (or created/deleted/purged one). Notify all
    1616             :  * backends about the change.
    1617             :  *
    1618             :  * @param id ID of the instance that changed
    1619             :  */
    1620             : void
    1621          42 : TMH_reload_instances (const char *id)
    1622             : {
    1623          42 :   struct GNUNET_DB_EventHeaderP es = {
    1624          42 :     es.size = ntohs (sizeof (es)),
    1625          42 :     es.type = ntohs (TALER_DBEVENT_MERCHANT_INSTANCE_SETTINGS)
    1626             :   };
    1627             : 
    1628          42 :   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    1629             :               "Generating instance settings notification: reload `%s'\n",
    1630             :               id);
    1631          84 :   TMH_db->event_notify (TMH_db->cls,
    1632             :                         &es,
    1633             :                         id,
    1634             :                         (NULL == id)
    1635             :                         ? 0
    1636          42 :                         : strlen (id) + 1);
    1637          42 : }
    1638             : 
    1639             : 
    1640             : /**
    1641             :  * Main function that will be run by the scheduler.
    1642             :  *
    1643             :  * @param cls closure
    1644             :  * @param args remaining command-line arguments
    1645             :  * @param cfgfile name of the configuration file used (for saving, can be
    1646             :  *        NULL!)
    1647             :  * @param config configuration
    1648             :  */
    1649             : static void
    1650          16 : run (void *cls,
    1651             :      char *const *args,
    1652             :      const char *cfgfile,
    1653             :      const struct GNUNET_CONFIGURATION_Handle *config)
    1654             : {
    1655             :   int fh;
    1656             :   enum TALER_MHD_GlobalOptions go;
    1657             :   int elen;
    1658             :   int alen;
    1659             :   const char *tok;
    1660             : 
    1661             :   (void) cls;
    1662             :   (void) args;
    1663             :   (void) cfgfile;
    1664          16 :   tok = getenv ("TALER_MERCHANT_TOKEN");
    1665          16 :   if ( (NULL != tok) &&
    1666           0 :        (NULL == TMH_default_auth) )
    1667           0 :     TMH_default_auth = GNUNET_strdup (tok);
    1668          16 :   cfg = config;
    1669          16 :   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    1670             :               "Starting taler-merchant-httpd\n");
    1671          16 :   go = TALER_MHD_GO_NONE;
    1672          16 :   if (merchant_connection_close)
    1673           0 :     go |= TALER_MHD_GO_FORCE_CONNECTION_CLOSE;
    1674          16 :   TALER_MHD_setup (go);
    1675             : 
    1676          16 :   result = GNUNET_SYSERR;
    1677          16 :   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
    1678             :                                  NULL);
    1679          16 :   if (GNUNET_OK !=
    1680          16 :       TALER_config_get_currency (cfg,
    1681             :                                  &TMH_currency))
    1682             :   {
    1683           0 :     GNUNET_SCHEDULER_shutdown ();
    1684           0 :     return;
    1685             :   }
    1686          16 :   if (GNUNET_OK !=
    1687          16 :       GNUNET_CONFIGURATION_get_value_time (cfg,
    1688             :                                            "merchant",
    1689             :                                            "LEGAL_PRESERVATION",
    1690             :                                            &TMH_legal_expiration))
    1691             :   {
    1692           0 :     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
    1693             :                                "merchant",
    1694             :                                "LEGAL_PRESERVATION");
    1695           0 :     GNUNET_SCHEDULER_shutdown ();
    1696           0 :     return;
    1697             :   }
    1698          16 :   if (GNUNET_YES ==
    1699          16 :       GNUNET_CONFIGURATION_get_value_yesno (cfg,
    1700             :                                             "merchant",
    1701             :                                             "FORCE_AUDIT"))
    1702           5 :     TMH_force_audit = GNUNET_YES;
    1703          16 :   TMH_templating_init ();
    1704          16 :   if (GNUNET_OK !=
    1705          16 :       TMH_spa_init ())
    1706             :   {
    1707           0 :     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    1708             :                 "Failed to load single page app\n");
    1709           0 :     GNUNET_SCHEDULER_shutdown ();
    1710           0 :     return;
    1711             :   }
    1712          16 :   TMH_statics_init ();
    1713          16 :   elen = TMH_EXCHANGES_init (config);
    1714          16 :   if (GNUNET_SYSERR == elen)
    1715             :   {
    1716           0 :     GNUNET_SCHEDULER_shutdown ();
    1717           0 :     return;
    1718             :   }
    1719          16 :   alen = TMH_AUDITORS_init (config);
    1720          16 :   if (GNUNET_SYSERR == alen)
    1721             :   {
    1722           0 :     GNUNET_SCHEDULER_shutdown ();
    1723           0 :     return;
    1724             :   }
    1725          16 :   if (0 == elen + alen)
    1726             :   {
    1727           0 :     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    1728             :                 "Fatal: no trusted exchanges and no trusted auditors configured. Exiting.\n");
    1729           0 :     GNUNET_SCHEDULER_shutdown ();
    1730           0 :     return;
    1731             :   }
    1732          16 :   if (NULL ==
    1733          16 :       (TMH_by_id_map = GNUNET_CONTAINER_multihashmap_create (4,
    1734             :                                                              GNUNET_YES)))
    1735             :   {
    1736           0 :     GNUNET_SCHEDULER_shutdown ();
    1737           0 :     return;
    1738             :   }
    1739          16 :   if (NULL ==
    1740          16 :       (TMH_db = TALER_MERCHANTDB_plugin_load (cfg)))
    1741             :   {
    1742           0 :     GNUNET_SCHEDULER_shutdown ();
    1743           0 :     return;
    1744             :   }
    1745          16 :   if (GNUNET_OK !=
    1746          16 :       TMH_db->connect (TMH_db->cls))
    1747             :   {
    1748           0 :     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    1749             :                 "Failed to initialize database connection\n");
    1750           0 :     GNUNET_SCHEDULER_shutdown ();
    1751           0 :     return;
    1752             :   }
    1753             :   {
    1754          16 :     struct GNUNET_DB_EventHeaderP es = {
    1755          16 :       es.size = ntohs (sizeof (es)),
    1756          16 :       es.type = ntohs (TALER_DBEVENT_MERCHANT_INSTANCE_SETTINGS)
    1757             :     };
    1758             : 
    1759          16 :     instance_eh = TMH_db->event_listen (TMH_db->cls,
    1760             :                                         &es,
    1761             :                                         GNUNET_TIME_UNIT_FOREVER_REL,
    1762             :                                         &load_instances,
    1763             :                                         NULL);
    1764             :   }
    1765          16 :   load_instances (NULL,
    1766             :                   NULL,
    1767             :                   0);
    1768             :   /* start watching reserves */
    1769          16 :   TMH_RESERVES_init ();
    1770          16 :   fh = TALER_MHD_bind (cfg,
    1771             :                        "merchant",
    1772             :                        &port);
    1773          16 :   if ( (0 == port) &&
    1774             :        (-1 == fh) )
    1775             :   {
    1776           0 :     GNUNET_SCHEDULER_shutdown ();
    1777           0 :     return;
    1778             :   }
    1779             : 
    1780             :   {
    1781             :     struct MHD_Daemon *mhd;
    1782             : 
    1783          16 :     mhd = MHD_start_daemon (MHD_USE_SUSPEND_RESUME | MHD_USE_DUAL_STACK
    1784             :                             | MHD_USE_AUTO,
    1785             :                             port,
    1786             :                             NULL, NULL,
    1787             :                             &url_handler, NULL,
    1788             :                             MHD_OPTION_LISTEN_SOCKET, fh,
    1789             :                             MHD_OPTION_NOTIFY_COMPLETED,
    1790             :                             &handle_mhd_completion_callback, NULL,
    1791             :                             MHD_OPTION_CONNECTION_TIMEOUT,
    1792             :                             (unsigned int) 10 /* 10s */,
    1793             :                             MHD_OPTION_END);
    1794          16 :     if (NULL == mhd)
    1795             :     {
    1796           0 :       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    1797             :                   "Failed to launch HTTP service. Is the port in use?\n");
    1798           0 :       GNUNET_SCHEDULER_shutdown ();
    1799           0 :       return;
    1800             :     }
    1801          16 :     result = GNUNET_OK;
    1802          16 :     TALER_MHD_daemon_start (mhd);
    1803             :   }
    1804             : }
    1805             : 
    1806             : 
    1807             : /**
    1808             :  * The main function of the serve tool
    1809             :  *
    1810             :  * @param argc number of arguments from the command line
    1811             :  * @param argv command line arguments
    1812             :  * @return 0 ok, non-zero on error
    1813             :  */
    1814             : int
    1815          21 : main (int argc,
    1816             :       char *const *argv)
    1817             : {
    1818             :   enum GNUNET_GenericReturnValue res;
    1819          21 :   struct GNUNET_GETOPT_CommandLineOption options[] = {
    1820          21 :     GNUNET_GETOPT_option_flag ('C',
    1821             :                                "connection-close",
    1822             :                                "force HTTP connections to be closed after each request",
    1823             :                                &merchant_connection_close),
    1824          21 :     GNUNET_GETOPT_option_timetravel ('T',
    1825             :                                      "timetravel"),
    1826          21 :     GNUNET_GETOPT_option_string ('a',
    1827             :                                  "auth",
    1828             :                                  "TOKEN",
    1829             :                                  "use TOKEN to initially authenticate access to the default instance (you can also set the TALER_MERCHANT_TOKEN environment variable instead)",
    1830             :                                  &TMH_default_auth),
    1831             :     GNUNET_GETOPT_OPTION_END
    1832             :   };
    1833             : 
    1834          21 :   TALER_OS_init ();
    1835          21 :   res = GNUNET_PROGRAM_run (argc, argv,
    1836             :                             "taler-merchant-httpd",
    1837             :                             "Taler merchant's HTTP backend interface",
    1838             :                             options,
    1839             :                             &run, NULL);
    1840          21 :   if (GNUNET_SYSERR == res)
    1841           0 :     return EXIT_INVALIDARGUMENT;
    1842          21 :   if (GNUNET_NO == res)
    1843           5 :     return EXIT_SUCCESS;
    1844          16 :   return (GNUNET_OK == result) ? EXIT_SUCCESS : 1;
    1845             : }

Generated by: LCOV version 1.14