anastasis

Credential backup and recovery protocol and service
Log | Files | Refs | Submodules | README | LICENSE

anastasis_api_backup_redux.c (128123B)


      1 /*
      2   This file is part of Anastasis
      3   Copyright (C) 2020-2023 Anastasis SARL
      4 
      5   Anastasis is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   Anastasis 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   Anastasis; see the file COPYING.GPL.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 /**
     17  * @file reducer/anastasis_api_backup_redux.c
     18  * @brief anastasis reducer backup api
     19  * @author Christian Grothoff
     20  * @author Dominik Meister
     21  * @author Dennis Neufeld
     22  */
     23 
     24 #include "platform.h"
     25 #include "anastasis_redux.h"
     26 #include "anastasis_api_redux.h"
     27 #include "anastasis_api_redux_state.h"
     28 #include <taler/taler_merchant_service.h>
     29 
     30 /**
     31  * How long do Anastasis providers store data if the service
     32  * is free? Must match #ANASTASIS_MAX_YEARS_STORAGE from
     33  * anastasis-httpd.h.
     34  */
     35 #define ANASTASIS_FREE_STORAGE GNUNET_TIME_relative_multiply ( \
     36           GNUNET_TIME_UNIT_YEARS, 5)
     37 
     38 /**
     39  * CPU limiter: do not evaluate more than 16k
     40  * possible policy combinations to find the "best"
     41  * policy.
     42  */
     43 #define MAX_EVALUATIONS (1024 * 16)
     44 
     45 
     46 #define GENERATE_STRING(STRING) #STRING,
     47 static const char *backup_strings[] = {
     48   ANASTASIS_BACKUP_STATES (GENERATE_STRING)
     49 };
     50 #undef GENERATE_STRING
     51 
     52 
     53 /**
     54  * Linked list of costs.
     55  */
     56 struct Costs
     57 {
     58 
     59   /**
     60    * Kept in a LL.
     61    */
     62   struct Costs *next;
     63 
     64   /**
     65    * Cost in one of the currencies.
     66    */
     67   struct TALER_Amount cost;
     68 };
     69 
     70 
     71 /**
     72  * Pick the single amount a provider contributes to an advisory total.
     73  *
     74  * A price list is not a sum: a provider offering both EUR and CHF wants
     75  * one or the other, not both, so adding every entry would tell the user
     76  * they owe twice over.  Each provider therefore contributes exactly one
     77  * amount --- in the preferred currency if it offers one, and otherwise in
     78  * its own primary currency, which is the honest answer that this part of
     79  * the backup will be settled separately.
     80  *
     81  * @param common state holding the user's preferred currency
     82  * @param al price list to pick from
     83  * @return the amount to add, NULL if @a al is empty
     84  */
     85 static const struct TALER_Amount *
     86 preferred_price (const struct ANASTASIS_ReduxCommon *common,
     87                  const struct TALER_AmountList *al)
     88 {
     89   if (NULL != common->preferred_currency)
     90   {
     91     const struct TALER_Amount *a;
     92 
     93     a = TALER_amount_list_find (al,
     94                                 common->preferred_currency);
     95     if (NULL != a)
     96       return a;
     97   }
     98   if (0 == al->tal_len)
     99     return NULL;
    100   return &al->tal[0];
    101 }
    102 
    103 
    104 /**
    105  * Check if two price lists offer the same prices, ignoring order.
    106  *
    107  * @param a first list
    108  * @param b second list
    109  * @return true if they agree on every currency
    110  */
    111 static bool
    112 amount_lists_equal (const struct TALER_AmountList *a,
    113                     const struct TALER_AmountList *b)
    114 {
    115   if (a->tal_len != b->tal_len)
    116     return false;
    117   for (unsigned int i = 0; i<a->tal_len; i++)
    118   {
    119     const struct TALER_Amount *o;
    120 
    121     o = TALER_amount_list_find (b,
    122                                 a->tal[i].currency);
    123     if ( (NULL == o) ||
    124          (0 != TALER_amount_cmp (&a->tal[i],
    125                                  o)) )
    126       return false;
    127   }
    128   return true;
    129 }
    130 
    131 
    132 /**
    133  * Add amount from @a cost to @a my_cost list.
    134  *
    135  * @param[in,out] my_cost pointer to list to modify
    136  * @param cost amount to add
    137  */
    138 static void
    139 add_cost (struct Costs **my_cost,
    140           const struct TALER_Amount *cost)
    141 {
    142   for (struct Costs *pos = *my_cost;
    143        NULL != pos;
    144        pos = pos->next)
    145   {
    146     if (GNUNET_OK !=
    147         TALER_amount_cmp_currency (&pos->cost,
    148                                    cost))
    149       continue;
    150     GNUNET_assert (0 <=
    151                    TALER_amount_add (&pos->cost,
    152                                      &pos->cost,
    153                                      cost));
    154     return;
    155   }
    156   {
    157     struct Costs *nc;
    158 
    159     nc = GNUNET_new (struct Costs);
    160     nc->cost = *cost;
    161     nc->next = *my_cost;
    162     *my_cost = nc;
    163   }
    164 }
    165 
    166 
    167 /**
    168  * Add amount from @a cost to @a my_cost list.
    169  *
    170  * @param[in,out] my_cost pointer to list to modify
    171  * @param cost amount to add
    172  */
    173 static void
    174 add_costs (struct Costs **my_cost,
    175            const struct Costs *costs)
    176 {
    177   for (const struct Costs *pos = costs;
    178        NULL != pos;
    179        pos = pos->next)
    180   {
    181     add_cost (my_cost,
    182               &pos->cost);
    183   }
    184 }
    185 
    186 
    187 enum ANASTASIS_BackupState
    188 ANASTASIS_backup_state_from_string_ (const char *state_string)
    189 {
    190   for (enum ANASTASIS_BackupState i = 0;
    191        i < sizeof (backup_strings) / sizeof(*backup_strings);
    192        i++)
    193     if (0 == strcmp (state_string,
    194                      backup_strings[i]))
    195       return i;
    196   return ANASTASIS_BACKUP_STATE_INVALID;
    197 }
    198 
    199 
    200 const char *
    201 ANASTASIS_backup_state_to_string_ (enum ANASTASIS_BackupState bs)
    202 {
    203   if ( (bs < 0) ||
    204        (bs >= sizeof (backup_strings) / sizeof(*backup_strings)) )
    205   {
    206     GNUNET_break_op (0);
    207     return NULL;
    208   }
    209   return backup_strings[bs];
    210 }
    211 
    212 
    213 /**
    214  * Transition @a rs to @a new_backup_state.
    215  *
    216  * @param[in,out] rs the state to transition
    217  * @param new_backup_state the state to transition to
    218  */
    219 static void
    220 set_state (struct ANASTASIS_ReduxState *rs,
    221            enum ANASTASIS_BackupState new_backup_state)
    222 {
    223   GNUNET_assert (ANASTASIS_RT_BACKUP == rs->type);
    224   rs->details.backup.state = new_backup_state;
    225 }
    226 
    227 
    228 /**
    229  * Returns an initial ANASTASIS backup state (CONTINENT_SELECTING).
    230  *
    231  * @param cfg handle for gnunet configuration
    232  * @return NULL on failure
    233  */
    234 json_t *
    235 ANASTASIS_backup_start (const struct GNUNET_CONFIGURATION_Handle *cfg)
    236 {
    237   json_t *initial_state;
    238   const char *external_reducer = ANASTASIS_REDUX_probe_external_reducer ();
    239 
    240   if (NULL != external_reducer)
    241   {
    242     int pipefd_stdout[2];
    243     pid_t pid = 0;
    244     int status;
    245     FILE *reducer_stdout;
    246 
    247     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    248                 "Using external reducer '%s' for backup start status\n",
    249                 external_reducer);
    250 
    251     GNUNET_assert (0 == pipe (pipefd_stdout));
    252     pid = fork ();
    253     if (pid == 0)
    254     {
    255       GNUNET_assert (0 ==
    256                      close (pipefd_stdout[0]));
    257       GNUNET_assert (STDOUT_FILENO ==
    258                      dup2 (pipefd_stdout[1],
    259                            STDOUT_FILENO));
    260       execlp (external_reducer,
    261               external_reducer,
    262               "-b",
    263               NULL);
    264       GNUNET_assert (0);
    265     }
    266 
    267     GNUNET_assert (0 ==
    268                    close (pipefd_stdout[1]));
    269     reducer_stdout = fdopen (pipefd_stdout[0],
    270                              "r");
    271     GNUNET_assert (NULL != reducer_stdout);
    272     {
    273       json_error_t err;
    274 
    275       initial_state = json_loadf (reducer_stdout,
    276                                   0,
    277                                   &err);
    278 
    279       if (NULL == initial_state)
    280       {
    281         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
    282                     "External reducer did not output valid JSON: %s:%d:%d %s\n",
    283                     err.source,
    284                     err.line,
    285                     err.column,
    286                     err.text);
    287         GNUNET_assert (0 == fclose (reducer_stdout));
    288         waitpid (pid, &status, 0);
    289         return NULL;
    290       }
    291     }
    292 
    293     GNUNET_assert (NULL != initial_state);
    294     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    295                 "Waiting for external reducer to terminate.\n");
    296     GNUNET_assert (0 == fclose (reducer_stdout));
    297     reducer_stdout = NULL;
    298     waitpid (pid, &status, 0);
    299 
    300     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    301                 "External reducer finished with exit status '%d'\n",
    302                 status);
    303     return initial_state;
    304   }
    305 
    306   (void) cfg;
    307   initial_state = ANASTASIS_REDUX_load_continents_ ();
    308   if (NULL == initial_state)
    309     return NULL;
    310   GNUNET_assert (
    311     0 ==
    312     json_object_set_new (initial_state,
    313                          "reducer_type",
    314                          json_string ("backup")));
    315   GNUNET_assert (
    316     0 ==
    317     json_object_set_new (
    318       initial_state,
    319       "backup_state",
    320       json_string (
    321         ANASTASIS_backup_state_to_string_ (
    322           ANASTASIS_BACKUP_STATE_CONTINENT_SELECTING))));
    323   return initial_state;
    324 }
    325 
    326 
    327 /**
    328  * Test if @a challenge_size is small enough for the provider's
    329  * @a size_limit_in_mb.
    330  *
    331  * We add 1024 to @a challenge_size here as a "safety margin" as
    332  * the encrypted challenge has some additional headers around it
    333  *
    334  * @param size_limit_in_mb provider's upload limit
    335  * @param challenge_size actual binary size of the challenge
    336  * @return true if this fits
    337  */
    338 static bool
    339 challenge_size_ok (uint32_t size_limit_in_mb,
    340                    size_t challenge_size)
    341 {
    342   return (size_limit_in_mb * 1024LLU * 1024LLU >=
    343           challenge_size + 1024LLU);
    344 }
    345 
    346 
    347 /**
    348  * DispatchHandler/Callback function which is called for a
    349  * "add_authentication" action.
    350  * Returns an #ANASTASIS_ReduxAction if operation is async.
    351  *
    352  * @param state state to operate on
    353  * @param arguments arguments to use for operation on state
    354  * @param cb callback to call during/after operation
    355  * @param cb_cls callback closure
    356  * @return NULL
    357  */
    358 static struct ANASTASIS_ReduxAction *
    359 add_authentication (struct ANASTASIS_ReduxState *rs,
    360                     const json_t *arguments,
    361                     ANASTASIS_ActionCallback cb,
    362                     void *cb_cls)
    363 {
    364   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
    365   const json_t *method;
    366   const char *method_type;
    367   const char *instructions;
    368   const char *mime_type = NULL;
    369   void *challenge;
    370   size_t challenge_size;
    371   struct GNUNET_JSON_Specification spec[] = {
    372     GNUNET_JSON_spec_string ("type",
    373                              &method_type),
    374     GNUNET_JSON_spec_string ("instructions",
    375                              &instructions),
    376     GNUNET_JSON_spec_varsize ("challenge",
    377                               &challenge,
    378                               &challenge_size),
    379     GNUNET_JSON_spec_mark_optional (
    380       GNUNET_JSON_spec_string ("mime_type",
    381                                &mime_type),
    382       NULL),
    383     GNUNET_JSON_spec_end ()
    384   };
    385 
    386   if (! rs->common.have_providers)
    387   {
    388     GNUNET_break (0);
    389     ANASTASIS_REDUX_fail_ (rs,
    390                            cb,
    391                            cb_cls,
    392                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
    393                            "'authentication_providers' missing");
    394     return NULL;
    395   }
    396 
    397   method = json_object_get (arguments,
    398                             "authentication_method");
    399   if (NULL == method)
    400   {
    401     GNUNET_break (0);
    402     ANASTASIS_REDUX_fail_ (rs,
    403                            cb,
    404                            cb_cls,
    405                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
    406                            "'authentication_method' required");
    407     return NULL;
    408   }
    409   if (GNUNET_OK !=
    410       GNUNET_JSON_parse (method,
    411                          spec,
    412                          NULL, NULL))
    413   {
    414     GNUNET_break (0);
    415     json_dumpf ((json_t *) method,
    416                 stderr,
    417                 JSON_INDENT (2));
    418     ANASTASIS_REDUX_fail_ (rs,
    419                            cb,
    420                            cb_cls,
    421                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
    422                            "'authentication_method' content malformed");
    423     return NULL;
    424   }
    425   /* Check we know at least one provider that supports this method */
    426   {
    427     bool found = false;
    428     bool too_big = false;
    429 
    430     for (unsigned int i = 0; i < rs->common.providers_len; i++)
    431     {
    432       const struct ANASTASIS_ReduxProvider *p = &rs->common.providers[i];
    433       const struct ANASTASIS_ReduxProviderConfig *cfg = &p->config;
    434 
    435       if (ANASTASIS_RPS_OK != p->status)
    436         continue;
    437       if (! p->have_config)
    438       {
    439         GNUNET_break (0);
    440         continue;
    441       }
    442       if (MHD_HTTP_OK != cfg->http_status)
    443         continue; /* skip providers that are down */
    444       if (0 == cfg->storage_limit_in_megabytes)
    445       {
    446         GNUNET_break (0);
    447         continue;
    448       }
    449       for (unsigned int j = 0; j < cfg->methods_len; j++)
    450         if (0 == strcmp (cfg->methods[j].type,
    451                          method_type))
    452         {
    453           found = true;
    454           break;
    455         }
    456       if (! challenge_size_ok (cfg->storage_limit_in_megabytes,
    457                                challenge_size))
    458       {
    459         /* Challenge data too big for this provider. Try to find another one.
    460            Note: we add 1024 to challenge-size here as a "safety margin" as
    461            the encrypted challenge has some additional headers around it */
    462         too_big = true;
    463         found = false;
    464       }
    465       if (found)
    466         break;
    467     }
    468     if (! found)
    469     {
    470       enum TALER_ErrorCode ec
    471         = too_big
    472           ? TALER_EC_ANASTASIS_REDUCER_CHALLENGE_DATA_TOO_BIG
    473           : TALER_EC_ANASTASIS_REDUCER_AUTHENTICATION_METHOD_NOT_SUPPORTED;
    474 
    475       ANASTASIS_REDUX_fail_ (rs,
    476                              cb,
    477                              cb_cls,
    478                              ec,
    479                              method_type);
    480       GNUNET_JSON_parse_free (spec);
    481       return NULL;
    482     }
    483   }
    484 
    485   /* append provided method to our array */
    486   {
    487     struct ANASTASIS_ReduxAuthMethod am = {
    488       .type = GNUNET_strdup (method_type),
    489       .instructions = GNUNET_strdup (instructions),
    490       .mime_type = (NULL == mime_type) ? NULL : GNUNET_strdup (mime_type),
    491       .challenge = GNUNET_memdup (challenge,
    492                                   challenge_size),
    493       .challenge_size = challenge_size
    494     };
    495 
    496     GNUNET_array_append (b->authentication_methods,
    497                          b->authentication_methods_len,
    498                          am);
    499     b->have_authentication_methods = true;
    500   }
    501   GNUNET_JSON_parse_free (spec);
    502   ANASTASIS_REDUX_return_ (rs,
    503                            cb,
    504                            cb_cls,
    505                            TALER_EC_NONE);
    506   return NULL;
    507 }
    508 
    509 
    510 /**
    511  * DispatchHandler/Callback function which is called for a
    512  * "delete_authentication" action.
    513  * Returns an #ANASTASIS_ReduxAction if operation is async.
    514  *
    515  * @param state state to operate on
    516  * @param arguments arguments to use for operation on state
    517  * @param cb callback to call during/after operation
    518  * @param cb_cls callback closure
    519  * @return NULL
    520  */
    521 static struct ANASTASIS_ReduxAction *
    522 del_authentication (struct ANASTASIS_ReduxState *rs,
    523                     const json_t *arguments,
    524                     ANASTASIS_ActionCallback cb,
    525                     void *cb_cls)
    526 {
    527   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
    528   const json_t *idx;
    529   json_int_t index;
    530 
    531   if (! b->have_authentication_methods)
    532   {
    533     ANASTASIS_REDUX_fail_ (rs,
    534                            cb,
    535                            cb_cls,
    536                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
    537                            "'authentication_methods' must be an array");
    538     return NULL;
    539   }
    540   if (NULL == arguments)
    541   {
    542     ANASTASIS_REDUX_fail_ (rs,
    543                            cb,
    544                            cb_cls,
    545                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
    546                            "arguments missing");
    547     return NULL;
    548   }
    549   idx = json_object_get (arguments,
    550                          "authentication_method");
    551   if ( (NULL == idx) ||
    552        (! json_is_integer (idx)) )
    553   {
    554     ANASTASIS_REDUX_fail_ (rs,
    555                            cb,
    556                            cb_cls,
    557                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
    558                            "'authentication_method' must be a number");
    559     return NULL;
    560   }
    561   index = json_integer_value (idx);
    562   if ( (index < 0) ||
    563        (index >= (json_int_t) b->authentication_methods_len) )
    564   {
    565     ANASTASIS_REDUX_fail_ (rs,
    566                            cb,
    567                            cb_cls,
    568                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
    569                            "removal failed");
    570     return NULL;
    571   }
    572   {
    573     struct ANASTASIS_ReduxAuthMethod *am
    574       = &b->authentication_methods[index];
    575 
    576     GNUNET_free (am->type);
    577     GNUNET_free (am->instructions);
    578     GNUNET_free (am->challenge);
    579     GNUNET_free (am->mime_type);
    580     memmove (am,
    581              am + 1,
    582              sizeof (*am) * (b->authentication_methods_len - index - 1));
    583     b->authentication_methods_len--;
    584   }
    585   ANASTASIS_REDUX_return_ (rs,
    586                            cb,
    587                            cb_cls,
    588                            TALER_EC_NONE);
    589   return NULL;
    590 }
    591 
    592 
    593 /* ********************** done_authentication ******************** */
    594 
    595 /**
    596  * Which provider would be used for the given challenge,
    597  * and at what cost?
    598  */
    599 struct PolicyEntry
    600 {
    601   /**
    602    * URL of the provider.
    603    */
    604   const char *provider_name;
    605 
    606   /**
    607    * Recovery fee.
    608    */
    609   struct Costs *usage_fee;
    610 };
    611 
    612 
    613 /**
    614  * Map from challenges to providers.
    615  */
    616 struct PolicyMap
    617 {
    618   /**
    619    * Kept in a DLL.
    620    */
    621   struct PolicyMap *next;
    622 
    623   /**
    624    * Kept in a DLL.
    625    */
    626   struct PolicyMap *prev;
    627 
    628   /**
    629    * Array of proividers selected for each challenge,
    630    * with associated costs.
    631    * Length of the array will be 'req_methods'.
    632    */
    633   struct PolicyEntry *providers;
    634 
    635   /**
    636    * Diversity score for this policy mapping.
    637    */
    638   unsigned int diversity;
    639 
    640 };
    641 
    642 
    643 /**
    644  * Array of challenges for a policy, and DLL with
    645  * possible mappings of challenges to providers.
    646  */
    647 struct Policy
    648 {
    649 
    650   /**
    651    * Kept in DLL of all possible policies.
    652    */
    653   struct Policy *next;
    654 
    655   /**
    656    * Kept in DLL of all possible policies.
    657    */
    658   struct Policy *prev;
    659 
    660   /**
    661    * Head of DLL.
    662    */
    663   struct PolicyMap *pm_head;
    664 
    665   /**
    666    * Tail of DLL.
    667    */
    668   struct PolicyMap *pm_tail;
    669 
    670   /**
    671    * Challenges selected for this policy.
    672    * Length of the array will be 'req_methods'.
    673    */
    674   unsigned int *challenges;
    675 
    676 };
    677 
    678 
    679 /**
    680  * Information for running done_authentication() logic.
    681  */
    682 struct PolicyBuilder
    683 {
    684   /**
    685    * State we are working on; provides the authentication providers
    686    * available overall.
    687    */
    688   const struct ANASTASIS_ReduxCommon *common;
    689 
    690   /**
    691    * Backup state we are working on; provides the authentication
    692    * methods the user entered, and receives the computed policies.
    693    */
    694   struct ANASTASIS_ReduxBackup *backup;
    695 
    696   /**
    697    * Head of DLL of all possible policies.
    698    */
    699   struct Policy *p_head;
    700 
    701   /**
    702    * Tail of DLL of all possible policies.
    703    */
    704   struct Policy *p_tail;
    705 
    706   /**
    707    * Array of length @e req_methods.
    708    */
    709   unsigned int *m_idx;
    710 
    711   /**
    712    * Array of length @e req_methods identifying a set of providers selected
    713    * for each authentication method, while we are trying to compute the
    714    * 'best' allocation of providers to authentication methods.
    715    * Only valid during the go_with() function.
    716    */
    717   const char **best_sel;
    718 
    719   /**
    720    * Error hint to return on failure. Set if @e ec is not #TALER_EC_NONE.
    721    */
    722   const char *hint;
    723 
    724   /**
    725    * Policy we are currently building maps for.
    726    */
    727   struct Policy *current_policy;
    728 
    729   /**
    730    * LL of costs associated with the currently preferred
    731    * policy.
    732    */
    733   struct Costs *best_cost;
    734 
    735   /**
    736    * Array of 'best' policy maps found so far,
    737    * ordered by policy.
    738    */
    739   struct PolicyMap *best_map;
    740 
    741   /**
    742    * Array of the currency policy maps under evaluation
    743    * by find_best_map().
    744    */
    745   struct PolicyMap *curr_map;
    746 
    747   /**
    748    * How many mappings have we evaluated so far?
    749    * Used to limit the computation by aborting after
    750    * #MAX_EVALUATIONS trials.
    751    */
    752   unsigned int evaluations;
    753 
    754   /**
    755    * Overall number of challenges provided by the user.
    756    */
    757   unsigned int num_methods;
    758 
    759   /**
    760    * Number of challenges that must be satisfied to recover the secret.
    761    * Derived from the total number of challenges entered by the user.
    762    */
    763   unsigned int req_methods;
    764 
    765   /**
    766    * Number of different Anastasis providers selected in @e best_sel.
    767    * Only valid during the go_with() function.
    768    */
    769   unsigned int best_diversity;
    770 
    771   /**
    772    * Number of identical challenges duplicated at
    773    * various providers in the best case. Smaller is
    774    * better.
    775    */
    776   unsigned int best_duplicates;
    777 
    778   /**
    779    * Error code to return, #TALER_EC_NONE on success.
    780    */
    781   enum TALER_ErrorCode ec;
    782 
    783 };
    784 
    785 
    786 /**
    787  * Free @a costs LL.
    788  *
    789  * @param[in] costs linked list to free
    790  */
    791 static void
    792 free_costs (struct Costs *costs)
    793 {
    794   while (NULL != costs)
    795   {
    796     struct Costs *next = costs->next;
    797 
    798     GNUNET_free (costs);
    799     costs = next;
    800   }
    801 }
    802 
    803 
    804 /**
    805  * Check if providers @a p1 and @a p2 have equivalent
    806  * methods and cost structures.
    807  *
    808  * @param pb policy builder with list of providers
    809  * @param p1 name of provider to compare
    810  * @param p2 name of provider to compare
    811  * @return true if the providers are fully equivalent
    812  */
    813 static bool
    814 equiv_provider (const struct PolicyBuilder *pb,
    815                 const char *p1,
    816                 const char *p2)
    817 {
    818   const struct ANASTASIS_ReduxProvider *j1;
    819   const struct ANASTASIS_ReduxProvider *j2;
    820   const struct ANASTASIS_ReduxProviderConfig *c1;
    821   const struct ANASTASIS_ReduxProviderConfig *c2;
    822 
    823   j1 = ANASTASIS_REDUX_provider_find_ (pb->common,
    824                                        p1);
    825   j2 = ANASTASIS_REDUX_provider_find_ (pb->common,
    826                                        p2);
    827   if ( (NULL == j1) ||
    828        (NULL == j2) ||
    829        (! j1->have_config) ||
    830        (! j2->have_config) )
    831   {
    832     GNUNET_break (0);
    833     return false;
    834   }
    835   c1 = &j1->config;
    836   c2 = &j2->config;
    837   /* Compare the whole price lists, not just the primary currency: two
    838      providers that agree on EUR but differ on which other currencies
    839      they take are not interchangeable for a user holding one of them. */
    840   if (! amount_lists_equal (&c1->truth_upload_fees,
    841                             &c2->truth_upload_fees))
    842     return false;
    843 
    844   if (c1->methods_len != c2->methods_len)
    845     return false;
    846   for (unsigned int i = 0; i < c1->methods_len; i++)
    847   {
    848     const struct ANASTASIS_ReduxMethodSpec *m1 = &c1->methods[i];
    849     bool matched = false;
    850 
    851     for (unsigned int j = 0; j < c2->methods_len; j++)
    852     {
    853       const struct ANASTASIS_ReduxMethodSpec *m2 = &c2->methods[j];
    854 
    855       if ( (0 == strcmp (m1->type,
    856                          m2->type)) &&
    857            amount_lists_equal (&m1->usage_fees,
    858                                &m2->usage_fees) )
    859       {
    860         matched = true;
    861         break;
    862       }
    863     }
    864     if (! matched)
    865       return false;
    866   }
    867   return true;
    868 }
    869 
    870 
    871 /**
    872  * Evaluate the cost/benefit of the provider selection in @a prov_sel
    873  * and if it is better then the best known one in @a pb, update @a pb.
    874  *
    875  * @param[in,out] pb our operational context
    876  * @param[in,out] prov_sel array of req_methods provider indices to complete
    877  */
    878 static void
    879 eval_provider_selection (struct PolicyBuilder *pb,
    880                          const char *prov_sel[])
    881 {
    882   unsigned int curr_diversity;
    883   struct PolicyEntry policy_ent[pb->req_methods];
    884 
    885   memset (policy_ent,
    886           0,
    887           sizeof (policy_ent));
    888   for (unsigned int i = 0; i < pb->req_methods; i++)
    889   {
    890     const struct ANASTASIS_ReduxAuthMethod *am
    891       = &pb->backup->authentication_methods[pb->m_idx[i]];
    892     const struct ANASTASIS_ReduxProvider *p;
    893     const struct ANASTASIS_ReduxProviderConfig *cfg;
    894     bool found = false;
    895 
    896     policy_ent[i].provider_name = prov_sel[i];
    897     p = ANASTASIS_REDUX_provider_find_ (pb->common,
    898                                         prov_sel[i]);
    899     if ( (NULL == p) ||
    900          (! p->have_config) ||
    901          (MHD_HTTP_OK != p->config.http_status) )
    902     {
    903       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
    904                   "Skipping provider %s: no suitable configuration\n",
    905                   prov_sel[i]);
    906       goto cleanup;
    907     }
    908     cfg = &p->config;
    909     for (unsigned int j = 0; j < cfg->methods_len; j++)
    910     {
    911       const struct ANASTASIS_ReduxMethodSpec *ms = &cfg->methods[j];
    912 
    913       if ( (0 == strcmp (ms->type,
    914                          am->type)) &&
    915            (challenge_size_ok (cfg->storage_limit_in_megabytes,
    916                                am->challenge_size) ) )
    917       {
    918         const struct TALER_Amount *uf;
    919         const struct TALER_Amount *tf;
    920 
    921         found = true;
    922         uf = preferred_price (pb->common,
    923                               &ms->usage_fees);
    924         tf = preferred_price (pb->common,
    925                               &cfg->truth_upload_fees);
    926         if (NULL != uf)
    927           add_cost (&policy_ent[i].usage_fee,
    928                     uf);
    929         if (NULL != tf)
    930           add_cost (&policy_ent[i].usage_fee,
    931                     tf);
    932       }
    933     }
    934     if (! found)
    935     {
    936       /* Provider does not OFFER this method, combination not possible.
    937          Cost is basically 'infinite', but we simply then skip this. */
    938       goto cleanup;
    939     }
    940   }
    941 
    942   /* calculate provider diversity by counting number of different
    943      providers selected */
    944   curr_diversity = 0;
    945   for (unsigned int i = 0; i < pb->req_methods; i++)
    946   {
    947     bool found = false;
    948 
    949     for (unsigned int j = 0; j < i; j++)
    950     {
    951       if (prov_sel[i] == prov_sel[j])
    952       {
    953         found = true;
    954         break;
    955       }
    956     }
    957     if (! found)
    958       curr_diversity++;
    959   }
    960 #if DEBUG
    961   fprintf (stderr,
    962            "Diversity: %u (best: %u)\n",
    963            curr_diversity,
    964            pb->best_diversity);
    965 #endif
    966   if (curr_diversity < pb->best_diversity)
    967   {
    968     /* do not allow combinations that are bad
    969        for provider diversity */
    970     goto cleanup;
    971   }
    972   if (curr_diversity > pb->best_diversity)
    973   {
    974     /* drop existing policies, they are all worse */
    975     struct PolicyMap *m;
    976 
    977     while (NULL != (m = pb->current_policy->pm_head))
    978     {
    979       GNUNET_CONTAINER_DLL_remove (pb->current_policy->pm_head,
    980                                    pb->current_policy->pm_tail,
    981                                    m);
    982       for (unsigned int i = 0; i<pb->req_methods; i++)
    983       {
    984         free_costs (m->providers[i].usage_fee);
    985         m->providers[i].usage_fee = NULL;
    986       }
    987       GNUNET_free (m->providers);
    988       GNUNET_free (m);
    989     }
    990     pb->best_diversity = curr_diversity;
    991   }
    992   if (NULL == pb->p_head)
    993   {
    994     /* For the first policy, check for equivalent
    995        policy mapping existing: we
    996      do not want to do spend CPU time investigating
    997      purely equivalent permutations */
    998     for (struct PolicyMap *m = pb->current_policy->pm_head;
    999          NULL != m;
   1000          m = m->next)
   1001     {
   1002       bool equiv = true;
   1003       for (unsigned int i = 0; i<pb->req_methods; i++)
   1004       {
   1005         if (! equiv_provider (pb,
   1006                               m->providers[i].provider_name,
   1007                               policy_ent[i].provider_name))
   1008         {
   1009           equiv = false;
   1010           break;
   1011         }
   1012       }
   1013       if (equiv)
   1014       {
   1015         /* equivalent to known allocation */
   1016         goto cleanup;
   1017       }
   1018     }
   1019   }
   1020 
   1021   /* Add possible mapping to result list */
   1022   {
   1023     struct PolicyMap *m;
   1024 
   1025     m = GNUNET_new (struct PolicyMap);
   1026     m->providers = GNUNET_new_array (pb->req_methods,
   1027                                      struct PolicyEntry);
   1028     memcpy (m->providers,
   1029             policy_ent,
   1030             sizeof (struct PolicyEntry) * pb->req_methods);
   1031     m->diversity = curr_diversity;
   1032     GNUNET_CONTAINER_DLL_insert (pb->current_policy->pm_head,
   1033                                  pb->current_policy->pm_tail,
   1034                                  m);
   1035   }
   1036   return;
   1037 cleanup:
   1038   for (unsigned int i = 0; i<pb->req_methods; i++)
   1039     free_costs (policy_ent[i].usage_fee);
   1040 }
   1041 
   1042 
   1043 /**
   1044  * Recursively compute possible combination(s) of provider candidates
   1045  * in @e prov_sel. The selection is complete up to index @a i.  Calls
   1046  * eval_provider_selection() upon a feasible provider selection for
   1047  * evaluation, resulting in "better" combinations being persisted in
   1048  * @a pb.
   1049  *
   1050  * @param[in,out] pb our operational context
   1051  * @param[in,out] prov_sel array of req_methods provider URLs to complete
   1052  * @param i index up to which @a prov_sel is already initialized
   1053  */
   1054 static void
   1055 provider_candidate (struct PolicyBuilder *pb,
   1056                     const char *prov_sel[],
   1057                     unsigned int i)
   1058 {
   1059   for (unsigned int k = 0; k < pb->common->providers_len; k++)
   1060   {
   1061     const struct ANASTASIS_ReduxProvider *p = &pb->common->providers[k];
   1062 
   1063     if ( (ANASTASIS_RPS_DISABLED == p->status) ||
   1064          (! p->have_config) ||
   1065          (MHD_HTTP_OK != p->config.http_status) )
   1066       continue;
   1067     prov_sel[i] = p->url.url;
   1068     if (i == pb->req_methods - 1)
   1069     {
   1070       eval_provider_selection (pb,
   1071                                prov_sel);
   1072       if (TALER_EC_NONE != pb->ec)
   1073         break;
   1074       continue;
   1075     }
   1076     provider_candidate (pb,
   1077                         prov_sel,
   1078                         i + 1);
   1079   }
   1080 }
   1081 
   1082 
   1083 /**
   1084  * Using the selection of authentication methods from @a pb in
   1085  * "m_idx", compute the best choice of providers.
   1086  *
   1087  * @param[in,out] pb our operational context
   1088  */
   1089 static void
   1090 go_with (struct PolicyBuilder *pb)
   1091 {
   1092   const char *prov_sel[pb->req_methods];
   1093   struct Policy *policy;
   1094 
   1095   /* compute provider selection */
   1096   policy = GNUNET_new (struct Policy);
   1097   policy->challenges = GNUNET_new_array (pb->req_methods,
   1098                                          unsigned int);
   1099   memcpy (policy->challenges,
   1100           pb->m_idx,
   1101           pb->req_methods * sizeof (unsigned int));
   1102   pb->current_policy = policy;
   1103   pb->best_diversity = 0;
   1104   provider_candidate (pb,
   1105                       prov_sel,
   1106                       0);
   1107   GNUNET_CONTAINER_DLL_insert (pb->p_head,
   1108                                pb->p_tail,
   1109                                policy);
   1110   pb->current_policy = NULL;
   1111 }
   1112 
   1113 
   1114 /**
   1115  * Recursively computes all possible subsets of length "req_methods"
   1116  * from an array of length "num_methods", calling "go_with" on each of
   1117  * those subsets (in "m_idx").
   1118  *
   1119  * @param[in,out] pb our operational context
   1120  * @param i offset up to which the "m_idx" has been computed
   1121  */
   1122 static void
   1123 method_candidate (struct PolicyBuilder *pb,
   1124                   unsigned int i)
   1125 {
   1126   unsigned int start;
   1127   unsigned int *m_idx = pb->m_idx;
   1128 
   1129   start = (i > 0) ? m_idx[i - 1] + 1 : 0;
   1130   for (unsigned int j = start; j < pb->num_methods; j++)
   1131   {
   1132     m_idx[i] = j;
   1133     if (i == pb->req_methods - 1)
   1134     {
   1135 #if DEBUG
   1136       fprintf (stderr,
   1137                "Suggesting: ");
   1138       for (unsigned int k = 0; k<pb->req_methods; k++)
   1139       {
   1140         fprintf (stderr,
   1141                  "%u ",
   1142                  m_idx[k]);
   1143       }
   1144       fprintf (stderr, "\n");
   1145 #endif
   1146       go_with (pb);
   1147       continue;
   1148     }
   1149     method_candidate (pb,
   1150                       i + 1);
   1151   }
   1152 }
   1153 
   1154 
   1155 /**
   1156  * Compare two cost lists.
   1157  *
   1158  * @param my cost to compare
   1159  * @param be cost to compare
   1160  * @return 0 if costs are estimated equal,
   1161  *         1 if @a my < @a be
   1162  *        -1 if @a my > @a be
   1163  */
   1164 static int
   1165 compare_costs (const struct Costs *my,
   1166                const struct Costs *be)
   1167 {
   1168   int ranking = 0;
   1169 
   1170   for (const struct Costs *cmp = be;
   1171        NULL != cmp;
   1172        cmp = cmp->next)
   1173   {
   1174     bool found = false;
   1175 
   1176     for (const struct Costs *pos = my;
   1177          NULL != pos;
   1178          pos = pos->next)
   1179     {
   1180       if (GNUNET_OK !=
   1181           TALER_amount_cmp_currency (&cmp->cost,
   1182                                      &pos->cost))
   1183         continue;
   1184       found = true;
   1185     }
   1186     if (! found)
   1187       ranking--;   /* new policy has no cost in this currency */
   1188   }
   1189 
   1190   for (const struct Costs *pos = my;
   1191        NULL != pos;
   1192        pos = pos->next)
   1193   {
   1194     bool found = false;
   1195 
   1196     for (const struct Costs *cmp = be;
   1197          NULL != cmp;
   1198          cmp = cmp->next)
   1199     {
   1200       if (GNUNET_OK !=
   1201           TALER_amount_cmp_currency (&cmp->cost,
   1202                                      &pos->cost))
   1203         continue;
   1204       found = true;
   1205       switch (TALER_amount_cmp (&cmp->cost,
   1206                                 &pos->cost))
   1207       {
   1208       case -1:   /* cmp < pos */
   1209         ranking--;
   1210         break;
   1211       case 0:
   1212         break;
   1213       case 1:   /* cmp > pos */
   1214         ranking++;
   1215         break;
   1216       }
   1217       break;
   1218     }
   1219     if (! found)
   1220       ranking++;   /* old policy has no cost in this currency */
   1221   }
   1222   if (0 == ranking)
   1223     return 0;
   1224   return (0 > ranking) ? -1 : 1;
   1225 }
   1226 
   1227 
   1228 /**
   1229  * Evaluate the combined policy map stack in the ``curr_map`` of @a pb
   1230  * and compare to the current best cost. If we are better, save the
   1231  * stack in the ``best_map``.
   1232  *
   1233  * @param[in,out] pb policy builder we evaluate for
   1234  * @param num_policies length of the ``curr_map`` array
   1235  */
   1236 static void
   1237 evaluate_map (struct PolicyBuilder *pb,
   1238               unsigned int num_policies)
   1239 {
   1240   struct Costs *my_cost = NULL;
   1241   unsigned int i = 0;
   1242   unsigned int duplicates = 0;
   1243   int ccmp;
   1244 
   1245 #if DEBUG
   1246   fprintf (stderr,
   1247            "Checking...\n");
   1248 #endif
   1249   /* calculate cost */
   1250   for (const struct Policy *p = pb->p_head;
   1251        NULL != p;
   1252        p = p->next)
   1253   {
   1254     const struct PolicyMap *pm = &pb->curr_map[i++];
   1255 
   1256 #if DEBUG
   1257     fprintf (stderr,
   1258              "Evaluating %p (%u): ",
   1259              p,
   1260              pm->diversity);
   1261     for (unsigned int k = 0; k<pb->req_methods; k++)
   1262     {
   1263       const struct PolicyEntry *pe = &pm->providers[k];
   1264 
   1265       fprintf (stderr,
   1266                "%u->%s ",
   1267                p->challenges[k],
   1268                pe->provider_name);
   1269     }
   1270     fprintf (stderr, "\n");
   1271 #endif
   1272     for (unsigned int j = 0; j<pb->req_methods; j++)
   1273     {
   1274       const struct PolicyEntry *pe = &pm->providers[j];
   1275       unsigned int cv = p->challenges[j];
   1276       bool found = false;
   1277       unsigned int i2 = 0;
   1278 
   1279       /* check for duplicates */
   1280       for (const struct Policy *p2 = pb->p_head;
   1281            p2 != p;
   1282            p2 = p2->next)
   1283       {
   1284         const struct PolicyMap *pm2 = &pb->curr_map[i2++];
   1285 
   1286         for (unsigned int j2 = 0; j2<pb->req_methods; j2++)
   1287         {
   1288           const struct PolicyEntry *pe2 = &pm2->providers[j2];
   1289           unsigned int cv2 = p2->challenges[j2];
   1290 
   1291           if (cv != cv2)
   1292             continue; /* different challenge */
   1293           if (0 == strcmp (pe->provider_name,
   1294                            pe2->provider_name))
   1295             found = true; /* same challenge&provider! */
   1296           else
   1297             duplicates++; /* penalty for same challenge at two providers */
   1298         }
   1299       }
   1300       if (! found)
   1301       {
   1302         add_costs (&my_cost,
   1303                    pe->usage_fee);
   1304       }
   1305     }
   1306   }
   1307 
   1308   ccmp = -1; /* non-zero if 'best_duplicates' is UINT_MAX */
   1309   if ( (UINT_MAX != pb->best_duplicates) &&
   1310        (0 > (ccmp = compare_costs (my_cost,
   1311                                    pb->best_cost))) )
   1312   {
   1313     /* new method not clearly better, do not use it */
   1314     free_costs (my_cost);
   1315 #if DEBUG
   1316     fprintf (stderr,
   1317              "... useless\n");
   1318 #endif
   1319     return;
   1320   }
   1321   if ( (0 == ccmp) &&
   1322        (duplicates > pb->best_duplicates) )
   1323   {
   1324     /* new method is cost-equal, but looses on duplicates,
   1325        do not use it */
   1326     free_costs (my_cost);
   1327 #if DEBUG
   1328     fprintf (stderr,
   1329              "... useless\n");
   1330 #endif
   1331     return;
   1332   }
   1333   /* new method is better (or first), set as best */
   1334 #if DEBUG
   1335   fprintf (stderr,
   1336            "New best: %u duplicates, %s cost\n",
   1337            duplicates,
   1338            TALER_amount2s (&my_cost->cost));
   1339 #endif
   1340   free_costs (pb->best_cost);
   1341   pb->best_cost = my_cost;
   1342   pb->best_duplicates = duplicates;
   1343   memcpy (pb->best_map,
   1344           pb->curr_map,
   1345           sizeof (struct PolicyMap) * num_policies);
   1346 }
   1347 
   1348 
   1349 /**
   1350  * Try all policy maps for @a pos and evaluate the
   1351  * resulting total cost, saving the best result in
   1352  * @a pb.
   1353  *
   1354  * @param[in,out] pb policy builder context
   1355  * @param pos policy we are currently looking at maps for
   1356  * @param off index of @a pos for the policy map
   1357  */
   1358 static void
   1359 find_best_map (struct PolicyBuilder *pb,
   1360                struct Policy *pos,
   1361                unsigned int off)
   1362 {
   1363   if (NULL == pos)
   1364   {
   1365     evaluate_map (pb,
   1366                   off);
   1367     pb->evaluations++;
   1368     return;
   1369   }
   1370   for (struct PolicyMap *pm = pos->pm_head;
   1371        NULL != pm;
   1372        pm = pm->next)
   1373   {
   1374     pb->curr_map[off] = *pm;
   1375     find_best_map (pb,
   1376                    pos->next,
   1377                    off + 1);
   1378     if (pb->evaluations >= MAX_EVALUATIONS)
   1379       break;
   1380   }
   1381 }
   1382 
   1383 
   1384 /**
   1385  * Select cheapest policy combinations and store them in the ``policies``
   1386  * of the backup state @a pb builds.
   1387  *
   1388  * @param[in,out] pb policy builder with our state
   1389  */
   1390 static void
   1391 select_policies (struct PolicyBuilder *pb)
   1392 {
   1393   unsigned int cnt = 0;
   1394 
   1395   for (struct Policy *p = pb->p_head;
   1396        NULL != p;
   1397        p = p->next)
   1398     cnt++;
   1399   {
   1400     struct PolicyMap best[cnt];
   1401     struct PolicyMap curr[cnt];
   1402     unsigned int off;
   1403 
   1404     pb->best_map = best;
   1405     pb->curr_map = curr;
   1406     pb->best_duplicates = UINT_MAX; /* worst */
   1407     find_best_map (pb,
   1408                    pb->p_head,
   1409                    0);
   1410     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   1411                 "Assessed %u/%u policies\n",
   1412                 pb->evaluations,
   1413                 (unsigned int) MAX_EVALUATIONS);
   1414     if (0 == pb->evaluations)
   1415     {
   1416       /* Some policy has no provider mapping at all, so
   1417          find_best_map() never filled in @e best. */
   1418       pb->ec = TALER_EC_ANASTASIS_REDUCER_AUTHENTICATION_METHOD_NOT_SUPPORTED;
   1419       pb->hint =
   1420         "no provider offers all of the selected authentication methods";
   1421       return;
   1422     }
   1423     off = 0;
   1424     for (struct Policy *p = pb->p_head;
   1425          NULL != p;
   1426          p = p->next)
   1427     {
   1428       struct PolicyMap *pm = &best[off++];
   1429       struct ANASTASIS_ReduxPolicy pol = {
   1430         .methods_len = pb->req_methods,
   1431         .methods = GNUNET_new_array (pb->req_methods,
   1432                                      struct ANASTASIS_ReduxPolicyMethod)
   1433       };
   1434 
   1435 #if DEBUG
   1436       fprintf (stderr,
   1437                "Best map (%u): ",
   1438                pm->diversity);
   1439       for (unsigned int k = 0; k<pb->req_methods; k++)
   1440       {
   1441         fprintf (stderr,
   1442                  "%u->%s ",
   1443                  p->challenges[k],
   1444                  pm->providers[k].provider_name);
   1445       }
   1446       fprintf (stderr, "\n");
   1447 #endif
   1448       /* Convert "best" selection into the 'policies' array */
   1449       for (unsigned int i = 0; i < pb->req_methods; i++)
   1450       {
   1451         struct ANASTASIS_ReduxPolicyMethod *pm2 = &pol.methods[i];
   1452 
   1453         pm2->authentication_method.idx = p->challenges[i];
   1454         ANASTASIS_REDUX_provider_url_set_ (&pm2->provider,
   1455                                            pm->providers[i].provider_name);
   1456       }
   1457       GNUNET_array_append (pb->backup->policies,
   1458                            pb->backup->policies_len,
   1459                            pol);
   1460       pb->backup->have_policies = true;
   1461     }
   1462   }
   1463 }
   1464 
   1465 
   1466 /**
   1467  * Clean up @a pb, in particular the policies DLL.
   1468  *
   1469  * @param[in] pb builder to clean up
   1470  */
   1471 static void
   1472 clean_pb (struct PolicyBuilder *pb)
   1473 {
   1474   struct Policy *p;
   1475 
   1476   while (NULL != (p = pb->p_head))
   1477   {
   1478     struct PolicyMap *pm;
   1479 
   1480     while (NULL != (pm = p->pm_head))
   1481     {
   1482       GNUNET_CONTAINER_DLL_remove (p->pm_head,
   1483                                    p->pm_tail,
   1484                                    pm);
   1485       for (unsigned int i = 0; i<pb->req_methods; i++)
   1486         free_costs (pm->providers[i].usage_fee);
   1487       GNUNET_free (pm->providers);
   1488       GNUNET_free (pm);
   1489     }
   1490     GNUNET_CONTAINER_DLL_remove (pb->p_head,
   1491                                  pb->p_tail,
   1492                                  p);
   1493     GNUNET_free (p->challenges);
   1494     GNUNET_free (p);
   1495   }
   1496   free_costs (pb->best_cost);
   1497 }
   1498 
   1499 
   1500 /**
   1501  * DispatchHandler/Callback function which is called for a
   1502  * "done_authentication" action.  Automaticially computes policies
   1503  * based on available Anastasis providers and challenges provided by
   1504  * the user.
   1505  *
   1506  * @param state state to operate on
   1507  * @param arguments arguments to use for operation on state
   1508  * @param cb callback to call during/after operation
   1509  * @param cb_cls callback closure
   1510  * @return NULL
   1511  */
   1512 static struct ANASTASIS_ReduxAction *
   1513 done_authentication (struct ANASTASIS_ReduxState *rs,
   1514                      const json_t *arguments,
   1515                      ANASTASIS_ActionCallback cb,
   1516                      void *cb_cls)
   1517 {
   1518   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   1519   struct PolicyBuilder pb = {
   1520     .ec = TALER_EC_NONE,
   1521     .common = &rs->common,
   1522     .backup = b
   1523   };
   1524   const json_t *providers;
   1525 
   1526   if (! rs->common.have_providers)
   1527   {
   1528     ANASTASIS_REDUX_fail_ (rs,
   1529                            cb,
   1530                            cb_cls,
   1531                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1532                            "'authentication_providers' must be provided");
   1533     return NULL;
   1534   }
   1535   if (! b->have_authentication_methods)
   1536   {
   1537     ANASTASIS_REDUX_fail_ (rs,
   1538                            cb,
   1539                            cb_cls,
   1540                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1541                            "'authentication_methods' must be provided");
   1542     return NULL;
   1543   }
   1544   pb.num_methods = b->authentication_methods_len;
   1545   switch (pb.num_methods)
   1546   {
   1547   case 0:
   1548     ANASTASIS_REDUX_fail_ (rs,
   1549                            cb,
   1550                            cb_cls,
   1551                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1552                            "'authentication_methods' must not be empty");
   1553     return NULL;
   1554   case 1:
   1555     ANASTASIS_REDUX_fail_ (rs,
   1556                            cb,
   1557                            cb_cls,
   1558                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1559                            "Two factor authentication (2-FA) is required");
   1560     return NULL;
   1561   case 2:
   1562     pb.req_methods = pb.num_methods;
   1563     break;
   1564   case 3:
   1565   case 4:
   1566     pb.req_methods = pb.num_methods - 1;
   1567     break;
   1568   case 5:
   1569   case 6:
   1570     pb.req_methods = pb.num_methods - 2;
   1571     break;
   1572   case 7:
   1573     pb.req_methods = pb.num_methods - 3;
   1574     break;
   1575   default:
   1576     /* cap at 4 for auto-generation, algorithm
   1577        to compute mapping gets too expensive
   1578        otherwise. */
   1579     pb.req_methods = 4;
   1580     break;
   1581   }
   1582   {
   1583     unsigned int m_idx[pb.req_methods];
   1584 
   1585     /* select req_methods from num_methods. */
   1586     pb.m_idx = m_idx;
   1587     method_candidate (&pb,
   1588                       0);
   1589   }
   1590   /* the computed policies replace whatever was there before */
   1591   ANASTASIS_REDUX_policies_clear_ (b);
   1592   b->have_policies = true;
   1593   select_policies (&pb);
   1594   clean_pb (&pb);
   1595   if (TALER_EC_NONE != pb.ec)
   1596   {
   1597     ANASTASIS_REDUX_fail_ (rs,
   1598                            cb,
   1599                            cb_cls,
   1600                            pb.ec,
   1601                            pb.hint);
   1602     return NULL;
   1603   }
   1604   ANASTASIS_REDUX_policy_providers_clear_ (b);
   1605   b->have_policy_providers = true;
   1606   providers = json_object_get (arguments,
   1607                                "providers");
   1608   if (NULL == providers)
   1609   {
   1610     /* Setup a providers array from all working providers */
   1611     for (unsigned int i = 0; i < rs->common.providers_len; i++)
   1612     {
   1613       const char *url = rs->common.providers[i].url.url;
   1614       struct ANASTASIS_ReduxPolicyProvider pp = { 0 };
   1615       struct ANASTASIS_CRYPTO_ProviderSaltP salt;
   1616 
   1617       if (GNUNET_OK !=
   1618           ANASTASIS_REDUX_lookup_salt_ (&rs->common,
   1619                                         url,
   1620                                         &salt))
   1621         continue; /* skip providers that are down */
   1622       ANASTASIS_REDUX_provider_url_set_ (&pp.provider_url,
   1623                                          url);
   1624       GNUNET_array_append (b->policy_providers,
   1625                            b->policy_providers_len,
   1626                            pp);
   1627     }
   1628   }
   1629   else
   1630   {
   1631     /* Setup a providers array from the requested providers */
   1632     size_t off;
   1633     json_t *url;
   1634 
   1635     json_array_foreach (providers, off, url)
   1636     {
   1637       struct ANASTASIS_ReduxPolicyProvider pp = { 0 };
   1638       struct ANASTASIS_CRYPTO_ProviderSaltP salt;
   1639       const char *url_str;
   1640 
   1641       url_str = json_string_value (url);
   1642       if ( (NULL == url_str) ||
   1643            (GNUNET_OK !=
   1644             ANASTASIS_REDUX_lookup_salt_ (&rs->common,
   1645                                           url_str,
   1646                                           &salt)) )
   1647       {
   1648         GNUNET_break (0);
   1649         ANASTASIS_REDUX_fail_ (rs,
   1650                                cb,
   1651                                cb_cls,
   1652                                TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1653                                "unworkable provider requested");
   1654         return NULL;
   1655       }
   1656       ANASTASIS_REDUX_provider_url_set_ (&pp.provider_url,
   1657                                          url_str);
   1658       GNUNET_array_append (b->policy_providers,
   1659                            b->policy_providers_len,
   1660                            pp);
   1661     }
   1662   }
   1663   if (0 == b->policy_providers_len)
   1664   {
   1665     ANASTASIS_REDUX_fail_ (rs,
   1666                            cb,
   1667                            cb_cls,
   1668                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1669                            "no workable providers in state");
   1670     return NULL;
   1671   }
   1672   set_state (rs,
   1673              ANASTASIS_BACKUP_STATE_POLICIES_REVIEWING);
   1674   ANASTASIS_REDUX_return_ (rs,
   1675                            cb,
   1676                            cb_cls,
   1677                            TALER_EC_NONE);
   1678   return NULL;
   1679 }
   1680 
   1681 
   1682 /* ******************** add_provider ******************* */
   1683 
   1684 
   1685 /**
   1686  * DispatchHandler/Callback function which is called for a
   1687  * "add_provider" action.  Adds another Anastasis provider
   1688  * to the list of available providers for storing information.
   1689  *
   1690  * @param state state to operate on
   1691  * @param arguments arguments with a provider URL to add
   1692  * @param cb callback to call during/after operation
   1693  * @param cb_cls callback closure
   1694  */
   1695 static struct ANASTASIS_ReduxAction *
   1696 add_provider (struct ANASTASIS_ReduxState *rs,
   1697               const json_t *arguments,
   1698               ANASTASIS_ActionCallback cb,
   1699               void *cb_cls)
   1700 {
   1701   if (ANASTASIS_add_provider_ (rs,
   1702                                arguments,
   1703                                cb,
   1704                                cb_cls))
   1705     return NULL;
   1706   return ANASTASIS_REDUX_backup_begin_ (rs,
   1707                                         NULL,
   1708                                         cb,
   1709                                         cb_cls);
   1710 }
   1711 
   1712 
   1713 /* ******************** add_policy ******************* */
   1714 
   1715 
   1716 /**
   1717  * DispatchHandler/Callback function which is called for a
   1718  * "add_policy" action.
   1719  *
   1720  * @param state state to operate on
   1721  * @param arguments arguments to use for operation on state
   1722  * @param cb callback to call during/after operation
   1723  * @param cb_cls callback closure
   1724  * @return NULL
   1725  */
   1726 static struct ANASTASIS_ReduxAction *
   1727 add_policy (struct ANASTASIS_ReduxState *rs,
   1728             const json_t *arguments,
   1729             ANASTASIS_ActionCallback cb,
   1730             void *cb_cls)
   1731 {
   1732   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   1733   const json_t *arg_array;
   1734   struct ANASTASIS_ReduxPolicy pol = { 0 };
   1735 
   1736   if (NULL == arguments)
   1737   {
   1738     GNUNET_break (0);
   1739     ANASTASIS_REDUX_fail_ (rs,
   1740                            cb,
   1741                            cb_cls,
   1742                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1743                            "arguments missing");
   1744     return NULL;
   1745   }
   1746   arg_array = json_object_get (arguments,
   1747                                "policy");
   1748   if (! json_is_array (arg_array))
   1749   {
   1750     GNUNET_break (0);
   1751     ANASTASIS_REDUX_fail_ (rs,
   1752                            cb,
   1753                            cb_cls,
   1754                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1755                            "'policy' not an array");
   1756     return NULL;
   1757   }
   1758   if (! b->have_policies)
   1759   {
   1760     GNUNET_break (0);
   1761     ANASTASIS_REDUX_fail_ (rs,
   1762                            cb,
   1763                            cb_cls,
   1764                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1765                            "'policies' not an array");
   1766     return NULL;
   1767   }
   1768   if (! rs->common.have_providers)
   1769   {
   1770     GNUNET_break (0);
   1771     ANASTASIS_REDUX_fail_ (rs,
   1772                            cb,
   1773                            cb_cls,
   1774                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1775                            "'auth_providers' not an object");
   1776     return NULL;
   1777   }
   1778   if (! b->have_authentication_methods)
   1779   {
   1780     GNUNET_break (0);
   1781     ANASTASIS_REDUX_fail_ (rs,
   1782                            cb,
   1783                            cb_cls,
   1784                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1785                            "'auth_methods' not an array");
   1786     return NULL;
   1787   }
   1788 
   1789   /* Add all methods from 'arg_array' to the new policy */
   1790   {
   1791     size_t aindex;
   1792     json_t *method;
   1793 
   1794     json_array_foreach (arg_array, aindex, method)
   1795     {
   1796       const char *provider_url;
   1797       uint32_t method_idx;
   1798       const char *method_type;
   1799       const struct ANASTASIS_ReduxProvider *p;
   1800       const struct ANASTASIS_ReduxProviderConfig *cfg;
   1801       struct GNUNET_JSON_Specification ispec[] = {
   1802         GNUNET_JSON_spec_string ("provider",
   1803                                  &provider_url),
   1804         GNUNET_JSON_spec_uint32 ("authentication_method",
   1805                                  &method_idx),
   1806         GNUNET_JSON_spec_end ()
   1807       };
   1808 
   1809       if (GNUNET_OK !=
   1810           GNUNET_JSON_parse (method,
   1811                              ispec,
   1812                              NULL, NULL))
   1813       {
   1814         GNUNET_break (0);
   1815         ANASTASIS_REDUX_policy_clear_ (&pol);
   1816         ANASTASIS_REDUX_fail_ (rs,
   1817                                cb,
   1818                                cb_cls,
   1819                                TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1820                                "'method' details malformed");
   1821         return NULL;
   1822       }
   1823 
   1824       p = ANASTASIS_REDUX_provider_find_ (&rs->common,
   1825                                           provider_url);
   1826       if (NULL == p)
   1827       {
   1828         GNUNET_break (0);
   1829         ANASTASIS_REDUX_policy_clear_ (&pol);
   1830         ANASTASIS_REDUX_fail_ (rs,
   1831                                cb,
   1832                                cb_cls,
   1833                                TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1834                                "provider URL unknown");
   1835         return NULL;
   1836       }
   1837       if ( (! p->have_config) ||
   1838            (ANASTASIS_RPS_OK != p->status) ||
   1839            (MHD_HTTP_OK != p->config.http_status) )
   1840         continue; /* skip provider, disabled or down */
   1841       cfg = &p->config;
   1842 
   1843       if (method_idx >= b->authentication_methods_len)
   1844       {
   1845         GNUNET_break (0);
   1846         ANASTASIS_REDUX_policy_clear_ (&pol);
   1847         ANASTASIS_REDUX_fail_ (rs,
   1848                                cb,
   1849                                cb_cls,
   1850                                TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1851                                "authentication method unknown");
   1852         return NULL;
   1853       }
   1854       method_type = b->authentication_methods[method_idx].type;
   1855 
   1856       {
   1857         bool found = false;
   1858 
   1859         for (unsigned int j = 0; j < cfg->methods_len; j++)
   1860           if (0 == strcmp (cfg->methods[j].type,
   1861                            method_type))
   1862           {
   1863             found = true;
   1864             break;
   1865           }
   1866         if (! found)
   1867         {
   1868           GNUNET_break (0);
   1869           ANASTASIS_REDUX_policy_clear_ (&pol);
   1870           ANASTASIS_REDUX_fail_ (
   1871             rs,
   1872             cb,
   1873             cb_cls,
   1874             TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1875             "selected provider does not support authentication method");
   1876           return NULL;
   1877         }
   1878       }
   1879       {
   1880         struct ANASTASIS_ReduxPolicyMethod pm = {
   1881           .authentication_method.idx = method_idx
   1882         };
   1883 
   1884         ANASTASIS_REDUX_provider_url_set_ (&pm.provider,
   1885                                            provider_url);
   1886         GNUNET_array_append (pol.methods,
   1887                              pol.methods_len,
   1888                              pm);
   1889       }
   1890     } /* end of json_array_foreach (arg_array, mindex, method) */
   1891   }
   1892 
   1893   /* add new policy to array of existing policies */
   1894   {
   1895     const json_t *idx;
   1896     unsigned int at;
   1897 
   1898     idx = json_object_get (arguments,
   1899                            "policy_index");
   1900     if ( (NULL == idx) ||
   1901          (! json_is_integer (idx)) )
   1902       at = b->policies_len;
   1903     else
   1904       at = GNUNET_MIN ((unsigned int) json_integer_value (idx),
   1905                        b->policies_len);
   1906     GNUNET_array_append (b->policies,
   1907                          b->policies_len,
   1908                          pol);
   1909     if (at != b->policies_len - 1)
   1910     {
   1911       /* shift the tail one to the right and drop the new entry in */
   1912       memmove (&b->policies[at + 1],
   1913                &b->policies[at],
   1914                sizeof (struct ANASTASIS_ReduxPolicy)
   1915                * (b->policies_len - at - 1));
   1916       b->policies[at] = pol;
   1917     }
   1918   }
   1919 
   1920   ANASTASIS_REDUX_return_ (rs,
   1921                            cb,
   1922                            cb_cls,
   1923                            TALER_EC_NONE);
   1924   return NULL;
   1925 }
   1926 
   1927 
   1928 /* ******************** update_policy ******************* */
   1929 
   1930 
   1931 /**
   1932  * DispatchHandler/Callback function which is called for a
   1933  * "update_policy" action.
   1934  *
   1935  * @param state state to operate on
   1936  * @param arguments arguments to use for operation on state
   1937  * @param cb callback to call during/after operation
   1938  * @param cb_cls callback closure
   1939  * @return NULL
   1940  */
   1941 static struct ANASTASIS_ReduxAction *
   1942 update_policy (struct ANASTASIS_ReduxState *rs,
   1943                const json_t *arguments,
   1944                ANASTASIS_ActionCallback cb,
   1945                void *cb_cls)
   1946 {
   1947   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   1948   const json_t *idx;
   1949   json_int_t index;
   1950 
   1951   if (NULL == arguments)
   1952   {
   1953     GNUNET_break (0);
   1954     ANASTASIS_REDUX_fail_ (rs,
   1955                            cb,
   1956                            cb_cls,
   1957                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1958                            "arguments missing");
   1959     return NULL;
   1960   }
   1961   idx = json_object_get (arguments,
   1962                          "policy_index");
   1963   if (! json_is_integer (idx))
   1964   {
   1965     GNUNET_break (0);
   1966     ANASTASIS_REDUX_fail_ (rs,
   1967                            cb,
   1968                            cb_cls,
   1969                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   1970                            "'policy_index' must be an integer");
   1971     return NULL;
   1972   }
   1973   index = json_integer_value (idx);
   1974   if (! b->have_policies)
   1975   {
   1976     GNUNET_break (0);
   1977     ANASTASIS_REDUX_fail_ (rs,
   1978                            cb,
   1979                            cb_cls,
   1980                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   1981                            "'policies' must be an array");
   1982     return NULL;
   1983   }
   1984   if ( (index < 0) ||
   1985        (index >= (json_int_t) b->policies_len) )
   1986   {
   1987     GNUNET_break (0);
   1988     ANASTASIS_REDUX_fail_ (rs,
   1989                            cb,
   1990                            cb_cls,
   1991                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
   1992                            "removal failed");
   1993     return NULL;
   1994   }
   1995   ANASTASIS_REDUX_policy_clear_ (&b->policies[index]);
   1996   memmove (&b->policies[index],
   1997            &b->policies[index + 1],
   1998            sizeof (struct ANASTASIS_ReduxPolicy)
   1999            * (b->policies_len - index - 1));
   2000   b->policies_len--;
   2001   return add_policy (rs,
   2002                      arguments,
   2003                      cb,
   2004                      cb_cls);
   2005 }
   2006 
   2007 
   2008 /* ******************** del_policy ******************* */
   2009 
   2010 
   2011 /**
   2012  * DispatchHandler/Callback function which is called for a
   2013  * "delete_policy" action.
   2014  *
   2015  * @param state state to operate on
   2016  * @param arguments arguments to use for operation on state
   2017  * @param cb callback to call during/after operation
   2018  * @param cb_cls callback closure
   2019  * @return NULL
   2020  */
   2021 static struct ANASTASIS_ReduxAction *
   2022 del_policy (struct ANASTASIS_ReduxState *rs,
   2023             const json_t *arguments,
   2024             ANASTASIS_ActionCallback cb,
   2025             void *cb_cls)
   2026 {
   2027   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   2028   const json_t *idx;
   2029   json_int_t index;
   2030 
   2031   if (NULL == arguments)
   2032   {
   2033     ANASTASIS_REDUX_fail_ (rs,
   2034                            cb,
   2035                            cb_cls,
   2036                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   2037                            "arguments missing");
   2038     return NULL;
   2039   }
   2040   idx = json_object_get (arguments,
   2041                          "policy_index");
   2042   if (! json_is_integer (idx))
   2043   {
   2044     ANASTASIS_REDUX_fail_ (rs,
   2045                            cb,
   2046                            cb_cls,
   2047                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   2048                            "'policy_index' must be an integer");
   2049     return NULL;
   2050   }
   2051   index = json_integer_value (idx);
   2052   if (! b->have_policies)
   2053   {
   2054     ANASTASIS_REDUX_fail_ (rs,
   2055                            cb,
   2056                            cb_cls,
   2057                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   2058                            "'policies' must be an array");
   2059     return NULL;
   2060   }
   2061   if ( (index < 0) ||
   2062        (index >= (json_int_t) b->policies_len) )
   2063   {
   2064     ANASTASIS_REDUX_fail_ (rs,
   2065                            cb,
   2066                            cb_cls,
   2067                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
   2068                            "removal failed");
   2069     return NULL;
   2070   }
   2071   ANASTASIS_REDUX_policy_clear_ (&b->policies[index]);
   2072   memmove (&b->policies[index],
   2073            &b->policies[index + 1],
   2074            sizeof (struct ANASTASIS_ReduxPolicy)
   2075            * (b->policies_len - index - 1));
   2076   b->policies_len--;
   2077   ANASTASIS_REDUX_return_ (rs,
   2078                            cb,
   2079                            cb_cls,
   2080                            TALER_EC_NONE);
   2081   return NULL;
   2082 }
   2083 
   2084 
   2085 /* ******************** del_challenge ******************* */
   2086 
   2087 
   2088 /**
   2089  * DispatchHandler/Callback function which is called for a
   2090  * "delete_challenge" action.
   2091  *
   2092  * @param state state to operate on
   2093  * @param arguments arguments to use for operation on state
   2094  * @param cb callback to call during/after operation
   2095  * @param cb_cls callback closure
   2096  * @return NULL
   2097  */
   2098 static struct ANASTASIS_ReduxAction *
   2099 del_challenge (struct ANASTASIS_ReduxState *rs,
   2100                const json_t *arguments,
   2101                ANASTASIS_ActionCallback cb,
   2102                void *cb_cls)
   2103 {
   2104   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   2105   const json_t *pidx;
   2106   const json_t *cidx;
   2107   json_int_t index;
   2108   struct ANASTASIS_ReduxPolicy *policy;
   2109 
   2110   if (NULL == arguments)
   2111   {
   2112     ANASTASIS_REDUX_fail_ (rs,
   2113                            cb,
   2114                            cb_cls,
   2115                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   2116                            "arguments missing");
   2117     return NULL;
   2118   }
   2119   pidx = json_object_get (arguments,
   2120                           "policy_index");
   2121   cidx = json_object_get (arguments,
   2122                           "challenge_index");
   2123   if (! json_is_integer (pidx))
   2124   {
   2125     ANASTASIS_REDUX_fail_ (rs,
   2126                            cb,
   2127                            cb_cls,
   2128                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   2129                            "'policy_index' must be an integer");
   2130     return NULL;
   2131   }
   2132   if (! json_is_integer (cidx))
   2133   {
   2134     ANASTASIS_REDUX_fail_ (rs,
   2135                            cb,
   2136                            cb_cls,
   2137                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   2138                            "'challenge_index' must be an integer");
   2139     return NULL;
   2140   }
   2141   index = json_integer_value (pidx);
   2142   if (! b->have_policies)
   2143   {
   2144     ANASTASIS_REDUX_fail_ (rs,
   2145                            cb,
   2146                            cb_cls,
   2147                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   2148                            "'policies' must be an array");
   2149     return NULL;
   2150   }
   2151   if ( (index < 0) ||
   2152        (index >= (json_int_t) b->policies_len) )
   2153   {
   2154     ANASTASIS_REDUX_fail_ (rs,
   2155                            cb,
   2156                            cb_cls,
   2157                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   2158                            "'policy_index' out of range");
   2159     return NULL;
   2160   }
   2161   policy = &b->policies[index];
   2162   index = json_integer_value (cidx);
   2163   if ( (index < 0) ||
   2164        (index >= (json_int_t) policy->methods_len) )
   2165   {
   2166     ANASTASIS_REDUX_fail_ (rs,
   2167                            cb,
   2168                            cb_cls,
   2169                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
   2170                            "removal failed");
   2171     return NULL;
   2172   }
   2173   {
   2174     struct ANASTASIS_ReduxPolicyMethod *pm = &policy->methods[index];
   2175 
   2176     ANASTASIS_REDUX_provider_url_clear_ (&pm->provider);
   2177     if (NULL != pm->truth)
   2178       ANASTASIS_truth_free (pm->truth);
   2179     memmove (pm,
   2180              pm + 1,
   2181              sizeof (*pm) * (policy->methods_len - index - 1));
   2182     policy->methods_len--;
   2183   }
   2184   ANASTASIS_REDUX_return_ (rs,
   2185                            cb,
   2186                            cb_cls,
   2187                            TALER_EC_NONE);
   2188   return NULL;
   2189 }
   2190 
   2191 
   2192 /* ********************** done_policy_review ***************** */
   2193 
   2194 
   2195 /**
   2196  * Calculate how many years of service we need
   2197  * from the desired @a expiration time,
   2198  * rounding up.
   2199  *
   2200  * @param expiration desired expiration time
   2201  * @return number of years of service to pay for
   2202 */
   2203 static unsigned int
   2204 expiration_to_years (struct GNUNET_TIME_Timestamp expiration)
   2205 {
   2206   struct GNUNET_TIME_Relative rem;
   2207   unsigned int years;
   2208 
   2209   rem = GNUNET_TIME_absolute_get_remaining (expiration.abs_time);
   2210   years = rem.rel_value_us / GNUNET_TIME_UNIT_YEARS.rel_value_us;
   2211   if (0 != rem.rel_value_us % GNUNET_TIME_UNIT_YEARS.rel_value_us)
   2212     years++;
   2213   return years;
   2214 }
   2215 
   2216 
   2217 /**
   2218  * Update @a state such that the earliest expiration for
   2219  * any truth or policy is @a expiration. Recalculate
   2220  * the ``upload_fees`` array with the associated costs.
   2221  *
   2222  * @param[in,out] state our state to update
   2223  * @param expiration new expiration to enforce
   2224  * @return #GNUNET_OK on success,
   2225  *         #GNUNET_SYSERR if the state is invalid
   2226  */
   2227 static enum GNUNET_GenericReturnValue
   2228 update_expiration_cost (struct ANASTASIS_ReduxState *rs,
   2229                         struct GNUNET_TIME_Timestamp expiration)
   2230 {
   2231   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   2232   struct Costs *costs = NULL;
   2233   unsigned int years;
   2234   bool is_free = true;
   2235 
   2236   if (! rs->common.have_providers)
   2237   {
   2238     GNUNET_break (0);
   2239     return GNUNET_SYSERR;
   2240   }
   2241 
   2242   years = expiration_to_years (expiration);
   2243 
   2244   /* Publish the currencies in which the *whole* backup can be settled
   2245      with one choice of currency, i.e. the intersection over the
   2246      providers that will actually be used.  An empty intersection is not
   2247      an error: it means the user will pay more than one order in more
   2248      than one currency, which is exactly what `upload_fees' then shows. */
   2249   {
   2250     bool first = true;
   2251 
   2252     for (unsigned int i = 0; i < rs->common.currencies_len; i++)
   2253       GNUNET_free (rs->common.currencies[i]);
   2254     GNUNET_array_grow (rs->common.currencies,
   2255                        rs->common.currencies_len,
   2256                        0);
   2257     rs->common.have_currencies = true;
   2258     for (unsigned int i = 0; i < rs->common.providers_len; i++)
   2259     {
   2260       const struct ANASTASIS_ReduxProvider *p = &rs->common.providers[i];
   2261 
   2262       if ( (ANASTASIS_RPS_OK != p->status) ||
   2263            (! p->have_config) ||
   2264            (MHD_HTTP_OK != p->config.http_status) )
   2265         continue;
   2266       if (first)
   2267       {
   2268         for (unsigned int j = 0; j < p->config.currencies_len; j++)
   2269           GNUNET_array_append (rs->common.currencies,
   2270                                rs->common.currencies_len,
   2271                                GNUNET_strdup (p->config.currencies[j]));
   2272         first = false;
   2273         continue;
   2274       }
   2275       for (unsigned int j = 0; j < rs->common.currencies_len;)
   2276       {
   2277         bool found = false;
   2278 
   2279         for (unsigned int k = 0; k < p->config.currencies_len; k++)
   2280           if (0 == strcasecmp (rs->common.currencies[j],
   2281                                p->config.currencies[k]))
   2282             found = true;
   2283         if (found)
   2284         {
   2285           j++;
   2286           continue;
   2287         }
   2288         GNUNET_free (rs->common.currencies[j]);
   2289         rs->common.currencies[j]
   2290           = rs->common.currencies[rs->common.currencies_len - 1];
   2291         GNUNET_array_grow (rs->common.currencies,
   2292                            rs->common.currencies_len,
   2293                            rs->common.currencies_len - 1);
   2294       }
   2295     }
   2296   }
   2297 
   2298   /* go over all providers and add up cost */
   2299   for (unsigned int i = 0; i < rs->common.providers_len; i++)
   2300   {
   2301     const struct ANASTASIS_ReduxProvider *p = &rs->common.providers[i];
   2302     const struct TALER_Amount *af;
   2303     struct TALER_Amount fee;
   2304 
   2305     if ( (ANASTASIS_RPS_OK != p->status) ||
   2306          (! p->have_config) ||
   2307          (MHD_HTTP_OK != p->config.http_status) )
   2308       continue; /* skip providers that are down or disabled */
   2309     af = preferred_price (&rs->common,
   2310                           &p->config.annual_fees);
   2311     if (NULL == af)
   2312       continue; /* provider is free */
   2313     if (0 >
   2314         TALER_amount_multiply (&fee,
   2315                                af,
   2316                                years))
   2317     {
   2318       GNUNET_break (0);
   2319       free_costs (costs);
   2320       return GNUNET_SYSERR;
   2321     }
   2322     add_cost (&costs,
   2323               &fee);
   2324   }
   2325 
   2326   /* go over all truths and add up cost */
   2327   {
   2328     unsigned int off = 0;
   2329     unsigned int len = 0;
   2330     struct AlreadySeen
   2331     {
   2332       unsigned int method;
   2333       const char *provider_url;
   2334     } *seen = NULL;
   2335 
   2336     for (unsigned int pidx = 0; pidx < b->policies_len; pidx++)
   2337     {
   2338       const struct ANASTASIS_ReduxPolicy *policy = &b->policies[pidx];
   2339 
   2340       for (unsigned int midx = 0; midx < policy->methods_len; midx++)
   2341       {
   2342         const struct ANASTASIS_ReduxPolicyMethod *pm = &policy->methods[midx];
   2343         const char *provider_url = pm->provider.url;
   2344         unsigned int method_idx = pm->authentication_method.idx;
   2345         const struct ANASTASIS_ReduxProvider *p;
   2346 
   2347         /* check if we have seen this one before */
   2348         {
   2349           bool found = false;
   2350 
   2351           for (unsigned int i = 0; i<off; i++)
   2352             if ( (seen[i].method == method_idx) &&
   2353                  (0 == strcmp (seen[i].provider_url,
   2354                                provider_url)) )
   2355               found = true;
   2356           if (found)
   2357             continue; /* skip */
   2358         }
   2359         if (off == len)
   2360         {
   2361           GNUNET_array_grow (seen,
   2362                              len,
   2363                              4 + len * 2);
   2364         }
   2365         seen[off].method = method_idx;
   2366         seen[off].provider_url = provider_url;
   2367         off++;
   2368         p = ANASTASIS_REDUX_provider_find_ (&rs->common,
   2369                                             provider_url);
   2370         if ( (NULL == p) ||
   2371              (! p->have_config) ||
   2372              (ANASTASIS_RPS_OK != p->status) ||
   2373              (MHD_HTTP_OK != p->config.http_status) )
   2374         {
   2375           GNUNET_break (0);
   2376           GNUNET_array_grow (seen,
   2377                              len,
   2378                              0);
   2379           free_costs (costs);
   2380           return GNUNET_SYSERR;
   2381         }
   2382         {
   2383           const struct TALER_Amount *tf;
   2384           struct TALER_Amount fee;
   2385 
   2386           tf = preferred_price (&rs->common,
   2387                                 &p->config.truth_upload_fees);
   2388           if (NULL == tf)
   2389             continue; /* provider stores truths for free */
   2390           if (0 >
   2391               TALER_amount_multiply (&fee,
   2392                                      tf,
   2393                                      years))
   2394           {
   2395             GNUNET_break (0);
   2396             GNUNET_array_grow (seen,
   2397                                len,
   2398                                0);
   2399             free_costs (costs);
   2400             return GNUNET_SYSERR;
   2401           }
   2402           add_cost (&costs,
   2403                     &fee);
   2404         }
   2405       }
   2406     }
   2407     GNUNET_array_grow (seen,
   2408                        len,
   2409                        0);
   2410   }
   2411 
   2412   /* convert 'costs' into state */
   2413   GNUNET_free (b->upload_fees);
   2414   b->upload_fees_len = 0;
   2415   b->have_upload_fees = true;
   2416   while (NULL != costs)
   2417   {
   2418     struct Costs *nxt = costs->next;
   2419 
   2420     if (! TALER_amount_is_zero (&costs->cost))
   2421     {
   2422       GNUNET_array_append (b->upload_fees,
   2423                            b->upload_fees_len,
   2424                            costs->cost);
   2425       is_free = false;
   2426     }
   2427     GNUNET_free (costs);
   2428     costs = nxt;
   2429   }
   2430 
   2431   if (is_free)
   2432     expiration = GNUNET_TIME_relative_to_timestamp (ANASTASIS_FREE_STORAGE);
   2433   b->expiration = expiration;
   2434   b->have_expiration = true;
   2435   return GNUNET_OK;
   2436 }
   2437 
   2438 
   2439 /**
   2440  * DispatchHandler/Callback function which is called for a
   2441  * "done_policy_review" action.
   2442  *
   2443  * @param state state to operate on
   2444  * @param arguments arguments to use for operation on state
   2445  * @param cb callback to call during/after operation
   2446  * @param cb_cls callback closure
   2447  * @return NULL
   2448  */
   2449 static struct ANASTASIS_ReduxAction *
   2450 done_policy_review (struct ANASTASIS_ReduxState *rs,
   2451                     const json_t *arguments,
   2452                     ANASTASIS_ActionCallback cb,
   2453                     void *cb_cls)
   2454 {
   2455   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   2456   struct GNUNET_TIME_Timestamp exp;
   2457 
   2458   if (0 == b->policies_len)
   2459   {
   2460     ANASTASIS_REDUX_fail_ (rs,
   2461                            cb,
   2462                            cb_cls,
   2463                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
   2464                            "no policies specified");
   2465     return NULL;
   2466   }
   2467   exp = b->have_expiration
   2468         ? b->expiration
   2469         : GNUNET_TIME_relative_to_timestamp (GNUNET_TIME_UNIT_YEARS);
   2470   if (GNUNET_TIME_absolute_is_zero (exp.abs_time))
   2471     exp = GNUNET_TIME_relative_to_timestamp (GNUNET_TIME_UNIT_YEARS);
   2472   if (GNUNET_OK !=
   2473       update_expiration_cost (rs,
   2474                               exp))
   2475   {
   2476     ANASTASIS_REDUX_fail_ (rs,
   2477                            cb,
   2478                            cb_cls,
   2479                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
   2480                            "could not calculate expiration cost");
   2481     return NULL;
   2482   }
   2483   set_state (rs,
   2484              ANASTASIS_BACKUP_STATE_SECRET_EDITING);
   2485   ANASTASIS_REDUX_return_ (rs,
   2486                            cb,
   2487                            cb_cls,
   2488                            TALER_EC_NONE);
   2489   return NULL;
   2490 }
   2491 
   2492 
   2493 /**
   2494  * Information we keep for an upload() operation.
   2495  */
   2496 struct UploadContext;
   2497 
   2498 
   2499 /**
   2500  * Maps a TruthUpload to a policy and recovery method where this
   2501  * truth is used.
   2502  */
   2503 struct PolicyMethodReference
   2504 {
   2505   /**
   2506    * Offset into the "policies" array.
   2507    */
   2508   unsigned int policy_index;
   2509 
   2510   /**
   2511    * Offset into the "methods" array (of the policy selected
   2512    * by @e policy_index).
   2513    */
   2514   unsigned int method_index;
   2515 
   2516 };
   2517 
   2518 
   2519 /**
   2520  * Entry we keep per truth upload.
   2521  */
   2522 struct TruthUpload
   2523 {
   2524 
   2525   /**
   2526    * Kept in a DLL.
   2527    */
   2528   struct TruthUpload *next;
   2529 
   2530   /**
   2531    * Kept in a DLL.
   2532    */
   2533   struct TruthUpload *prev;
   2534 
   2535   /**
   2536    * Handle to the actual upload operation.
   2537    */
   2538   struct ANASTASIS_TruthUpload *tu;
   2539 
   2540   /**
   2541    * Upload context this operation is part of.
   2542    */
   2543   struct UploadContext *uc;
   2544 
   2545   /**
   2546    * Truth resulting from the upload, if any.
   2547    */
   2548   struct ANASTASIS_Truth *t;
   2549 
   2550   /**
   2551    * A taler://pay/-URI with a request to pay the annual fee for
   2552    * the service.  Set if payment is required.
   2553    */
   2554   char *payment_request;
   2555 
   2556   /**
   2557    * Which policies and methods does this truth affect?
   2558    */
   2559   struct PolicyMethodReference *policies;
   2560 
   2561   /**
   2562    * Where are we uploading to?
   2563    */
   2564   char *provider_url;
   2565 
   2566   /**
   2567    * Which challenge object are we uploading?
   2568    */
   2569   uint32_t am_idx;
   2570 
   2571   /**
   2572    * Length of the @e policies array.
   2573    */
   2574   unsigned int policies_length;
   2575 
   2576   /**
   2577    * Status of the upload.
   2578    */
   2579   enum ANASTASIS_UploadStatus us;
   2580 
   2581   /**
   2582    * Taler error code of the upload.
   2583    */
   2584   enum TALER_ErrorCode ec;
   2585 
   2586 };
   2587 
   2588 
   2589 /**
   2590  * Information we keep for an upload() operation.
   2591  */
   2592 struct UploadContext
   2593 {
   2594   /**
   2595    * Recovery action returned to caller for aborting the operation.
   2596    */
   2597   struct ANASTASIS_ReduxAction ra;
   2598 
   2599   /**
   2600    * Function to call upon completion.
   2601    */
   2602   ANASTASIS_ActionCallback cb;
   2603 
   2604   /**
   2605    * Closure for @e cb.
   2606    */
   2607   void *cb_cls;
   2608 
   2609   /**
   2610    * Our state; we own it.
   2611    */
   2612   struct ANASTASIS_ReduxState *rs;
   2613 
   2614   /**
   2615    * Master secret sharing operation, NULL if not yet running.
   2616    */
   2617   struct ANASTASIS_SecretShare *ss;
   2618 
   2619   /**
   2620    * Head of DLL of truth uploads.
   2621    */
   2622   struct TruthUpload *tues_head;
   2623 
   2624   /**
   2625    * Tail of DLL of truth uploads.
   2626    */
   2627   struct TruthUpload *tues_tail;
   2628 
   2629   /**
   2630    * Timeout to use for the operation, from the arguments.
   2631    */
   2632   struct GNUNET_TIME_Relative timeout;
   2633 
   2634   /**
   2635    * For how many years should we pay?
   2636    */
   2637   unsigned int years;
   2638 
   2639 };
   2640 
   2641 
   2642 /**
   2643  * Function called when the #upload transition is being aborted.
   2644  *
   2645  * @param cls a `struct UploadContext`
   2646  */
   2647 static void
   2648 upload_cancel_cb (void *cls)
   2649 {
   2650   struct UploadContext *uc = cls;
   2651   struct TruthUpload *tue;
   2652 
   2653   while (NULL != (tue = uc->tues_head))
   2654   {
   2655     GNUNET_CONTAINER_DLL_remove (uc->tues_head,
   2656                                  uc->tues_tail,
   2657                                  tue);
   2658     if (NULL != tue->tu)
   2659     {
   2660       ANASTASIS_truth_upload_cancel (tue->tu);
   2661       tue->tu = NULL;
   2662     }
   2663     if (NULL != tue->t)
   2664     {
   2665       ANASTASIS_truth_free (tue->t);
   2666       tue->t = NULL;
   2667     }
   2668     GNUNET_free (tue->provider_url);
   2669     GNUNET_free (tue->payment_request);
   2670     GNUNET_free (tue->policies);
   2671     GNUNET_free (tue);
   2672   }
   2673   if (NULL != uc->ss)
   2674   {
   2675     ANASTASIS_secret_share_cancel (uc->ss);
   2676     uc->ss = NULL;
   2677   }
   2678   ANASTASIS_REDUX_state_free_ (uc->rs);
   2679   GNUNET_free (uc);
   2680 }
   2681 
   2682 
   2683 /**
   2684  * Return the state of @a uc to the application and dispose of @a uc.
   2685  *
   2686  * @param[in] uc context to finish
   2687  * @param ec error code to report alongside the state
   2688  */
   2689 static void
   2690 uc_return (struct UploadContext *uc,
   2691            enum TALER_ErrorCode ec)
   2692 {
   2693   struct ANASTASIS_ReduxState *rs = uc->rs;
   2694   ANASTASIS_ActionCallback cb = uc->cb;
   2695   void *cb_cls = uc->cb_cls;
   2696 
   2697   uc->rs = NULL;
   2698   upload_cancel_cb (uc);
   2699   ANASTASIS_REDUX_return_ (rs,
   2700                            cb,
   2701                            cb_cls,
   2702                            ec);
   2703 }
   2704 
   2705 
   2706 /**
   2707  * Report an error to the application and dispose of @a uc.
   2708  *
   2709  * @param[in] uc context to finish
   2710  * @param ec error to report
   2711  * @param detail human-readable detail, may be NULL
   2712  */
   2713 static void
   2714 uc_fail (struct UploadContext *uc,
   2715          enum TALER_ErrorCode ec,
   2716          const char *detail)
   2717 {
   2718   ANASTASIS_ActionCallback cb = uc->cb;
   2719   void *cb_cls = uc->cb_cls;
   2720 
   2721   upload_cancel_cb (uc);
   2722   ANASTASIS_redux_fail_ (cb,
   2723                          cb_cls,
   2724                          ec,
   2725                          detail);
   2726 }
   2727 
   2728 
   2729 /**
   2730  * Duplicate the truth @a t.  Truths are shared between the policies
   2731  * that use them, but each `struct ANASTASIS_Truth` has a single owner,
   2732  * so the state gets its own copy.
   2733  *
   2734  * @param t truth to copy
   2735  * @return a copy of @a t
   2736  */
   2737 static struct ANASTASIS_Truth *
   2738 truth_dup (const struct ANASTASIS_Truth *t)
   2739 {
   2740   json_t *jt = ANASTASIS_truth_to_json (t);
   2741   struct ANASTASIS_Truth *r;
   2742 
   2743   GNUNET_assert (NULL != jt);
   2744   r = ANASTASIS_truth_from_json (jt);
   2745   GNUNET_assert (NULL != r);
   2746   json_decref (jt);
   2747   return r;
   2748 }
   2749 
   2750 
   2751 /**
   2752  * Take all of the ongoing truth uploads and store them in the @a uc
   2753  * state, so that they survive a round-trip through the application.
   2754  *
   2755  * @param[in,out] uc context to take truth uploads from and to update state of
   2756  */
   2757 static void
   2758 serialize_truth (struct UploadContext *uc)
   2759 {
   2760   struct ANASTASIS_ReduxBackup *b = &uc->rs->details.backup;
   2761 
   2762   for (struct TruthUpload *tue = uc->tues_head;
   2763        NULL != tue;
   2764        tue = tue->next)
   2765   {
   2766     if (NULL == tue->t)
   2767       continue;
   2768     for (unsigned int i = 0; i<tue->policies_length; i++)
   2769     {
   2770       const struct PolicyMethodReference *pmr = &tue->policies[i];
   2771       struct ANASTASIS_ReduxPolicy *policy;
   2772       struct ANASTASIS_ReduxPolicyMethod *pm;
   2773 
   2774       GNUNET_assert (pmr->policy_index < b->policies_len);
   2775       policy = &b->policies[pmr->policy_index];
   2776       GNUNET_assert (pmr->method_index < policy->methods_len);
   2777       pm = &policy->methods[pmr->method_index];
   2778       if (NULL != pm->truth)
   2779         ANASTASIS_truth_free (pm->truth);
   2780       pm->truth = truth_dup (tue->t);
   2781       pm->upload_status = tue->us;
   2782     }
   2783   }
   2784 }
   2785 
   2786 
   2787 /**
   2788  * Test if the given @a provider_url is used by any of the
   2789  * authentication methods and thus the provider should be
   2790  * considered mandatory for storing the policy.
   2791  *
   2792  * @param state state to inspect
   2793  * @param provider_url provider to test
   2794  * @return false if the provider can be removed from policy
   2795  *   upload considerations without causing a problem
   2796  */
   2797 static bool
   2798 provider_required (const struct ANASTASIS_ReduxState *rs,
   2799                    const char *provider_url)
   2800 {
   2801   const struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   2802 
   2803   for (unsigned int pidx = 0; pidx < b->policies_len; pidx++)
   2804   {
   2805     const struct ANASTASIS_ReduxPolicy *policy = &b->policies[pidx];
   2806 
   2807     for (unsigned int midx = 0; midx < policy->methods_len; midx++)
   2808       if (0 == strcmp (policy->methods[midx].provider.url,
   2809                        provider_url))
   2810         return true;
   2811   }
   2812   return false;
   2813 }
   2814 
   2815 
   2816 /**
   2817  * All truth uploads are done, begin with uploading the policy.
   2818  *
   2819  * @param[in,out] uc context for the operation
   2820  */
   2821 static void
   2822 share_secret (struct UploadContext *uc);
   2823 
   2824 
   2825 /**
   2826  * Function called with the results of a #ANASTASIS_secret_share().
   2827  *
   2828  * @param cls closure with a `struct UploadContext *`
   2829  * @param sr share result
   2830  */
   2831 static void
   2832 secret_share_result_cb (void *cls,
   2833                         const struct ANASTASIS_ShareResult *sr)
   2834 {
   2835   struct UploadContext *uc = cls;
   2836   struct ANASTASIS_ReduxBackup *b = &uc->rs->details.backup;
   2837 
   2838   uc->ss = NULL;
   2839   switch (sr->ss)
   2840   {
   2841   case ANASTASIS_SHARE_STATUS_SUCCESS:
   2842     /* Just to be safe, delete the "core_secret" so that it is not
   2843        accidentally preserved anywhere */
   2844     json_decref (b->core_secret);
   2845     b->core_secret = NULL;
   2846     for (unsigned int i = 0; i < b->success_details_len; i++)
   2847       ANASTASIS_REDUX_provider_url_clear_ (
   2848         &b->success_details[i].provider_url);
   2849     GNUNET_free (b->success_details);
   2850     b->success_details_len = 0;
   2851     b->have_success_details = true;
   2852     for (unsigned int i = 0; i<sr->details.success.num_providers; i++)
   2853     {
   2854       const struct ANASTASIS_ProviderSuccessStatus *pssi
   2855         = &sr->details.success.pss[i];
   2856       struct ANASTASIS_ReduxSuccessDetail d = {
   2857         .policy_version = pssi->policy_version,
   2858         .policy_expiration = pssi->policy_expiration
   2859       };
   2860 
   2861       ANASTASIS_REDUX_provider_url_set_ (&d.provider_url,
   2862                                          pssi->provider_url);
   2863       GNUNET_array_append (b->success_details,
   2864                            b->success_details_len,
   2865                            d);
   2866     }
   2867     set_state (uc->rs,
   2868                ANASTASIS_BACKUP_STATE_BACKUP_FINISHED);
   2869     uc_return (uc,
   2870                TALER_EC_NONE);
   2871     return;
   2872   case ANASTASIS_SHARE_STATUS_PAYMENT_REQUIRED:
   2873     set_state (uc->rs,
   2874                ANASTASIS_BACKUP_STATE_POLICIES_PAYING);
   2875     serialize_truth (uc);
   2876     ANASTASIS_REDUX_policy_payment_requests_clear_ (b);
   2877     b->have_policy_payment_requests = true;
   2878     for (unsigned int i = 0; i<
   2879          sr->details.payment_required.payment_requests_length; i++)
   2880     {
   2881       const struct ANASTASIS_SharePaymentRequest *spr;
   2882       struct ANASTASIS_ReduxPolicyPaymentRequest ppr = { 0 };
   2883 
   2884       spr = &sr->details.payment_required.payment_requests[i];
   2885       ppr.payto = GNUNET_strdup (spr->payment_request_url);
   2886       ANASTASIS_REDUX_provider_url_set_ (&ppr.provider,
   2887                                          spr->provider_url);
   2888       GNUNET_array_append (b->policy_payment_requests,
   2889                            b->policy_payment_requests_len,
   2890                            ppr);
   2891       for (unsigned int off = 0; off < b->policy_providers_len; off++)
   2892       {
   2893         struct ANASTASIS_ReduxPolicyProvider *pp = &b->policy_providers[off];
   2894 
   2895         if (0 == strcmp (pp->provider_url.url,
   2896                          spr->provider_url))
   2897         {
   2898           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
   2899                       "Remembering payment secret for provider `%s'\n",
   2900                       spr->provider_url);
   2901           pp->payment_secret = spr->payment_secret;
   2902           pp->have_payment_secret = true;
   2903         }
   2904       }
   2905     }
   2906     uc_return (uc,
   2907                TALER_EC_NONE);
   2908     return;
   2909   case ANASTASIS_SHARE_STATUS_PROVIDER_FAILED:
   2910     {
   2911       json_t *details;
   2912       ANASTASIS_ActionCallback cb;
   2913       void *cb_cls;
   2914 
   2915       if (! provider_required (uc->rs,
   2916                                sr->details.provider_failure.provider_url))
   2917       {
   2918         /* try again without that provider */
   2919         struct ANASTASIS_ReduxProvider *p;
   2920 
   2921         p = ANASTASIS_REDUX_provider_find_ (
   2922           &uc->rs->common,
   2923           sr->details.provider_failure.provider_url);
   2924         if (NULL == p)
   2925           GNUNET_break (0);
   2926         else
   2927           p->status = ANASTASIS_RPS_DISABLED;
   2928         for (unsigned int idx = 0; idx < b->policy_providers_len; idx++)
   2929         {
   2930           struct ANASTASIS_ReduxPolicyProvider *pp
   2931             = &b->policy_providers[idx];
   2932 
   2933           if (0 == strcmp (sr->details.provider_failure.provider_url,
   2934                            pp->provider_url.url))
   2935           {
   2936             ANASTASIS_REDUX_provider_url_clear_ (&pp->provider_url);
   2937             memmove (pp,
   2938                      pp + 1,
   2939                      sizeof (*pp) * (b->policy_providers_len - idx - 1));
   2940             b->policy_providers_len--;
   2941             break;
   2942           }
   2943         }
   2944         share_secret (uc);
   2945         return;
   2946       }
   2947       details = GNUNET_JSON_PACK (
   2948         GNUNET_JSON_pack_uint64 ("http_status",
   2949                                  sr->details.provider_failure.http_status),
   2950         GNUNET_JSON_pack_uint64 ("code",
   2951                                  sr->details.provider_failure.ec),
   2952         GNUNET_JSON_pack_string ("hint",
   2953                                  TALER_ErrorCode_get_hint (
   2954                                    sr->details.provider_failure.ec)),
   2955         GNUNET_JSON_pack_string ("provider_url",
   2956                                  sr->details.provider_failure.provider_url));
   2957       cb = uc->cb;
   2958       cb_cls = uc->cb_cls;
   2959       upload_cancel_cb (uc);
   2960       cb (cb_cls,
   2961           TALER_EC_ANASTASIS_REDUCER_BACKUP_PROVIDER_FAILED,
   2962           details);
   2963       json_decref (details);
   2964     }
   2965     return;
   2966   default:
   2967     GNUNET_break (0);
   2968     uc_fail (uc,
   2969              TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE,
   2970              "unexpected share result");
   2971     return;
   2972   }
   2973 }
   2974 
   2975 
   2976 /**
   2977  * All truth uploads are done, begin with uploading the policy.
   2978  *
   2979  * @param[in,out] uc context for the operation
   2980  */
   2981 static void
   2982 share_secret (struct UploadContext *uc)
   2983 {
   2984   struct ANASTASIS_ReduxBackup *b = &uc->rs->details.backup;
   2985   unsigned int policies_len = b->policies_len;
   2986   unsigned int pds_len = b->policy_providers_len;
   2987   struct GNUNET_TIME_Relative timeout = GNUNET_TIME_UNIT_ZERO;
   2988 
   2989   if ( (NULL == uc->rs->common.identity_attributes) ||
   2990        (NULL == b->core_secret) ||
   2991        (! b->have_policies) )
   2992   {
   2993     uc_fail (uc,
   2994              TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   2995              "State parsing failed when preparing to share secret");
   2996     return;
   2997   }
   2998   if (b->have_pay_arguments &&
   2999       b->pay_arguments.have_timeout)
   3000     timeout = b->pay_arguments.timeout;
   3001   if (0 == policies_len)
   3002   {
   3003     uc_fail (uc,
   3004              TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3005              "State parsing failed checks when preparing to share secret");
   3006     return;
   3007   }
   3008   if (0 == pds_len)
   3009   {
   3010     uc_fail (uc,
   3011              TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3012              "no workable providers in state");
   3013     return;
   3014   }
   3015 
   3016   {
   3017     struct ANASTASIS_Policy *vpolicies[policies_len];
   3018     const struct ANASTASIS_Policy *policies[policies_len];
   3019     struct ANASTASIS_ProviderDetails pds[pds_len];
   3020 
   3021     /* initialize policies/vpolicies arrays */
   3022     memset (pds,
   3023             0,
   3024             sizeof (pds));
   3025     for (unsigned int i = 0; i<policies_len; i++)
   3026     {
   3027       const struct ANASTASIS_ReduxPolicy *policy = &b->policies[i];
   3028       unsigned int methods_len = policy->methods_len;
   3029 
   3030       if (0 == methods_len)
   3031       {
   3032         GNUNET_break (0);
   3033         for (unsigned int k = 0; k<i; k++)
   3034           ANASTASIS_policy_destroy (vpolicies[k]);
   3035         uc_fail (uc,
   3036                  TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3037                  "'methods' must be an array of sane length");
   3038         return;
   3039       }
   3040       {
   3041         struct ANASTASIS_Policy *p;
   3042         struct ANASTASIS_Truth *truths[methods_len];
   3043         const struct ANASTASIS_Truth *ctruths[methods_len];
   3044 
   3045         for (unsigned int j = 0; j<methods_len; j++)
   3046         {
   3047           const struct ANASTASIS_ReduxPolicyMethod *pm = &policy->methods[j];
   3048 
   3049           if (NULL != pm->truth)
   3050           {
   3051             /* Truth we already have in the state */
   3052             truths[j] = truth_dup (pm->truth);
   3053           }
   3054           else
   3055           {
   3056             bool found = false;
   3057             /* Maybe we never stored the truth; find it in our DLL */
   3058             for (struct TruthUpload *tue = uc->tues_head;
   3059                  NULL != tue;
   3060                  tue = tue->next)
   3061             {
   3062               GNUNET_break (NULL != tue->t);
   3063               if ( (tue->am_idx == pm->authentication_method.idx) &&
   3064                    (0 == strcmp (pm->provider.url,
   3065                                  tue->provider_url)) )
   3066               {
   3067                 truths[j] = truth_dup (tue->t);
   3068                 found = true;
   3069                 break;
   3070               }
   3071             }
   3072             if (! found)
   3073             {
   3074               GNUNET_break (0);
   3075               for (unsigned int k = 0; k<j; k++)
   3076                 ANASTASIS_truth_free (truths[k]);
   3077               for (unsigned int k = 0; k<i; k++)
   3078                 ANASTASIS_policy_destroy (vpolicies[k]);
   3079               uc_fail (uc,
   3080                        TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3081                        "'truth' failed to decode");
   3082               return;
   3083             }
   3084           }
   3085           ctruths[j] = truths[j];
   3086         }
   3087         p = ANASTASIS_policy_create (ctruths,
   3088                                      methods_len);
   3089         vpolicies[i] = p;
   3090         policies[i] = p;
   3091         for (unsigned int k = 0; k<methods_len; k++)
   3092           ANASTASIS_truth_free (truths[k]);
   3093       }
   3094     }
   3095 
   3096     /* initialize 'pds' array */
   3097     for (unsigned int i = 0; i<pds_len; i++)
   3098     {
   3099       const struct ANASTASIS_ReduxPolicyProvider *pp
   3100         = &b->policy_providers[i];
   3101 
   3102       pds[i].provider_url = pp->provider_url.url;
   3103       if (pp->have_payment_secret)
   3104         pds[i].payment_secret = pp->payment_secret;
   3105       if (GNUNET_OK !=
   3106           ANASTASIS_REDUX_lookup_salt_ (&uc->rs->common,
   3107                                         pds[i].provider_url,
   3108                                         &pds[i].provider_salt))
   3109       {
   3110         GNUNET_break (0);
   3111         for (unsigned int p = 0; p<policies_len; p++)
   3112           ANASTASIS_policy_destroy (vpolicies[p]);
   3113         uc_fail (uc,
   3114                  TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3115                  "'providers' entry malformed");
   3116         return;
   3117       }
   3118     }
   3119 
   3120     {
   3121       char *secret;
   3122       size_t secret_size;
   3123 
   3124       secret = json_dumps (b->core_secret,
   3125                            JSON_COMPACT | JSON_SORT_KEYS);
   3126       GNUNET_assert (NULL != secret);
   3127       secret_size = strlen (secret);
   3128       uc->ss = ANASTASIS_secret_share (ANASTASIS_REDUX_ctx_,
   3129                                        uc->rs->common.identity_attributes,
   3130                                        pds,
   3131                                        pds_len,
   3132                                        policies,
   3133                                        policies_len,
   3134                                        uc->years,
   3135                                        timeout,
   3136                                        &secret_share_result_cb,
   3137                                        uc,
   3138                                        b->secret_name,
   3139                                        secret,
   3140                                        secret_size);
   3141       GNUNET_free (secret);
   3142     }
   3143     for (unsigned int i = 0; i<policies_len; i++)
   3144       ANASTASIS_policy_destroy (vpolicies[i]);
   3145   }
   3146   if (NULL == uc->ss)
   3147   {
   3148     GNUNET_break (0);
   3149     uc_fail (uc,
   3150              TALER_EC_GENERIC_INTERNAL_INVARIANT_FAILURE,
   3151              "Failed to begin secret sharing");
   3152     return;
   3153   }
   3154 }
   3155 
   3156 
   3157 /**
   3158  * Some truth uploads require payment, serialize state and
   3159  * request payment to be executed by the application.
   3160  *
   3161  * @param[in,out] uc context for the operation
   3162  */
   3163 static void
   3164 request_truth_payment (struct UploadContext *uc)
   3165 {
   3166   struct ANASTASIS_ReduxBackup *b = &uc->rs->details.backup;
   3167 
   3168   serialize_truth (uc);
   3169   ANASTASIS_REDUX_payments_clear_ (b);
   3170   b->have_payments = true;
   3171   for (struct TruthUpload *tue = uc->tues_head;
   3172        NULL != tue;
   3173        tue = tue->next)
   3174   {
   3175     char *pr;
   3176 
   3177     if (NULL == tue->payment_request)
   3178       continue;
   3179     pr = GNUNET_strdup (tue->payment_request);
   3180     GNUNET_array_append (b->payments,
   3181                          b->payments_len,
   3182                          pr);
   3183   }
   3184   set_state (uc->rs,
   3185              ANASTASIS_BACKUP_STATE_TRUTHS_PAYING);
   3186   uc_return (uc,
   3187              TALER_EC_NONE);
   3188 }
   3189 
   3190 
   3191 /**
   3192  * We may be finished with all (active) asynchronous operations.
   3193  * Check if any are pending and continue accordingly.
   3194  *
   3195  * @param[in,out] uc context for the operation
   3196  */
   3197 static void
   3198 check_upload_finished (struct UploadContext *uc)
   3199 {
   3200   bool pay = false;
   3201   bool active = false;
   3202 
   3203   for (struct TruthUpload *tue = uc->tues_head;
   3204        NULL != tue;
   3205        tue = tue->next)
   3206   {
   3207     if (TALER_EC_NONE != tue->ec)
   3208     {
   3209       ANASTASIS_ActionCallback cb = uc->cb;
   3210       void *cb_cls = uc->cb_cls;
   3211       enum TALER_ErrorCode ec = tue->ec;
   3212 
   3213       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
   3214                   "Truth upload failed with error %d\n",
   3215                   (int) ec);
   3216       upload_cancel_cb (uc);
   3217       cb (cb_cls,
   3218           ec,
   3219           NULL);
   3220       return;
   3221     }
   3222     if (NULL != tue->tu)
   3223       active = true;
   3224     if (NULL != tue->payment_request)
   3225       pay = true;
   3226   }
   3227   if (active)
   3228     return;
   3229   if (pay)
   3230   {
   3231     request_truth_payment (uc);
   3232     return;
   3233   }
   3234   share_secret (uc);
   3235 }
   3236 
   3237 
   3238 /**
   3239  * Upload result information.  The resulting truth object can be used
   3240  * to create policies.  If payment is required, the @a taler_pay_url
   3241  * is returned and the operation must be retried after payment.
   3242  * Callee MUST free @a t using ANASTASIS_truth_free().
   3243  *
   3244  * @param cls closure with a `struct TruthUpload`
   3245  * @param t truth object to create policies, NULL on failure
   3246  * @param ud upload details
   3247  */
   3248 static void
   3249 truth_upload_cb (void *cls,
   3250                  struct ANASTASIS_Truth *t,
   3251                  const struct ANASTASIS_UploadDetails *ud)
   3252 {
   3253   struct TruthUpload *tue = cls;
   3254 
   3255   tue->tu = NULL;
   3256   tue->t = t;
   3257   tue->ec = ud->ec;
   3258   tue->us = ud->us;
   3259   if (ANASTASIS_US_PAYMENT_REQUIRED == ud->us)
   3260   {
   3261     tue->payment_request = GNUNET_strdup (
   3262       ud->details.payment.payment_request);
   3263   }
   3264   check_upload_finished (tue->uc);
   3265 }
   3266 
   3267 
   3268 /**
   3269  * Check if we still need to create a new truth object for the truth
   3270  * identified by @a provider_url and @a am_idx. If so, create it from
   3271  * @a truth for policy reference @a pmr. If such a truth object
   3272  * already exists, append @a pmr to its list of reasons.
   3273  *
   3274  * @param[in,out] uc our upload context
   3275  * @param pmr policy method combination that requires the truth
   3276  * @param provider_url the URL of the Anastasis provider to upload
   3277  *                     the truth to, used to check for existing entries
   3278  * @param am_idx index of the authentication method, used to check for existing entries
   3279  * @param[in] truth object representing already uploaded truth, reference captured!
   3280  * @param[in,out] async_truth pointer to counter with the number of ongoing uploads,
   3281  *                updated
   3282  * @param auth_method object with the challenge details, to generate the truth
   3283  * @return #GNUNET_SYSERR error requiring abort,
   3284  *         #GNUNET_OK on success
   3285  */
   3286 static int
   3287 add_truth_object (struct UploadContext *uc,
   3288                   const struct PolicyMethodReference *pmr,
   3289                   const char *provider_url,
   3290                   uint32_t am_idx,
   3291                   const struct ANASTASIS_ReduxPolicyMethod *pm,
   3292                   unsigned int *async_truth,
   3293                   const struct ANASTASIS_ReduxAuthMethod *auth_method)
   3294 {
   3295   /* check if we are already uploading this truth */
   3296   struct TruthUpload *tue;
   3297   bool must_upload;
   3298 
   3299   for (tue = uc->tues_head;
   3300        NULL != tue;
   3301        tue = tue->next)
   3302   {
   3303     if ( (0 == strcmp (tue->provider_url,
   3304                        provider_url)) &&
   3305          (am_idx == tue->am_idx) )
   3306     {
   3307       GNUNET_array_append (tue->policies,
   3308                            tue->policies_length,
   3309                            *pmr);
   3310       break;
   3311     }
   3312   }
   3313 
   3314   if (NULL == tue)
   3315   {
   3316     /* Create new entry */
   3317     tue = GNUNET_new (struct TruthUpload);
   3318 
   3319     GNUNET_CONTAINER_DLL_insert (uc->tues_head,
   3320                                  uc->tues_tail,
   3321                                  tue);
   3322     tue->uc = uc;
   3323     tue->policies = GNUNET_new (struct PolicyMethodReference);
   3324     *tue->policies = *pmr;
   3325     tue->provider_url = GNUNET_strdup (provider_url);
   3326     tue->am_idx = am_idx;
   3327     tue->policies_length = 1;
   3328   }
   3329 
   3330   must_upload = (ANASTASIS_US_SUCCESS != pm->upload_status);
   3331 
   3332   if (NULL == tue->t)
   3333     tue->t = truth_dup (pm->truth);
   3334 
   3335   if ( (NULL != tue->tu) &&
   3336        (! must_upload) )
   3337   {
   3338     ANASTASIS_truth_upload_cancel (tue->tu);
   3339     (*async_truth)--;
   3340     tue->tu = NULL;
   3341     return GNUNET_OK;
   3342   }
   3343 
   3344   if ( (NULL == tue->tu) &&
   3345        (must_upload) )
   3346   {
   3347     struct ANASTASIS_CRYPTO_ProviderSaltP salt;
   3348     struct ANASTASIS_CRYPTO_UserIdentifierP id;
   3349 
   3350     if (GNUNET_OK !=
   3351         ANASTASIS_REDUX_lookup_salt_ (&uc->rs->common,
   3352                                       provider_url,
   3353                                       &salt))
   3354     {
   3355       GNUNET_break (0);
   3356       return GNUNET_SYSERR;
   3357     }
   3358     if (NULL == uc->rs->common.identity_attributes)
   3359     {
   3360       GNUNET_break (0);
   3361       return GNUNET_SYSERR;
   3362     }
   3363     ANASTASIS_CRYPTO_user_identifier_derive (
   3364       uc->rs->common.identity_attributes,
   3365       &salt,
   3366       &id);
   3367     tue->tu = ANASTASIS_truth_upload3 (ANASTASIS_REDUX_ctx_,
   3368                                        &id,
   3369                                        tue->t,
   3370                                        auth_method->challenge,
   3371                                        auth_method->challenge_size,
   3372                                        uc->years,
   3373                                        uc->timeout,
   3374                                        &truth_upload_cb,
   3375                                        tue);
   3376     tue->t = NULL;
   3377     (*async_truth)++;
   3378   }
   3379 
   3380   if ( (NULL != tue->tu) &&
   3381        (NULL != tue->t) )
   3382   {
   3383     /* no point in having both */
   3384     ANASTASIS_truth_free (tue->t);
   3385     tue->t = NULL;
   3386   }
   3387   return GNUNET_OK;
   3388 }
   3389 
   3390 
   3391 /**
   3392  * Check if we still need to upload the truth identified by
   3393  * @a provider_url and @a am_idx. If so, upload it for
   3394  * policy reference @a pmr. If the upload is already queued,
   3395  * append @a pmr to its list of reasons.
   3396  *
   3397  * @param[in,out] uc our upload context
   3398  * @param pmr policy method combination that requires the truth
   3399  * @param provider_url the URL of the Anastasis provider to upload
   3400  *                     the truth to, used to check for existing entries
   3401  * @param am_idx index of the authentication method, used to check for existing entries
   3402  * @param auth_method object with the challenge details, to generate the truth
   3403  * @return #GNUNET_SYSERR on error requiring abort, in which case @a uc
   3404  *           has already been disposed of,
   3405  *         #GNUNET_NO if no new truth upload was generated (@a pmr was appended)
   3406  *         #GNUNET_OK if a new truth upload was initiated
   3407  */
   3408 static int
   3409 check_truth_upload (struct UploadContext *uc,
   3410                     const struct PolicyMethodReference *pmr,
   3411                     const char *provider_url,
   3412                     uint32_t am_idx,
   3413                     const struct ANASTASIS_ReduxAuthMethod *auth_method)
   3414 {
   3415   const json_t *user_id = uc->rs->common.identity_attributes;
   3416   struct TruthUpload *tue;
   3417 
   3418   if (NULL == user_id)
   3419   {
   3420     GNUNET_break (0);
   3421     upload_cancel_cb (uc);
   3422     return GNUNET_SYSERR;
   3423   }
   3424 
   3425   /* check if we are already uploading this truth */
   3426   for (tue = uc->tues_head;
   3427        NULL != tue;
   3428        tue = tue->next)
   3429   {
   3430     if ( (0 == strcmp (tue->provider_url,
   3431                        provider_url)) &&
   3432          (am_idx == tue->am_idx) )
   3433     {
   3434       GNUNET_array_append (tue->policies,
   3435                            tue->policies_length,
   3436                            *pmr);
   3437       return GNUNET_NO;
   3438     }
   3439   }
   3440 
   3441   /* need new upload */
   3442   tue = GNUNET_new (struct TruthUpload);
   3443   {
   3444     struct ANASTASIS_CRYPTO_ProviderSaltP provider_salt;
   3445     struct ANASTASIS_CRYPTO_UserIdentifierP id;
   3446 
   3447     GNUNET_CONTAINER_DLL_insert (uc->tues_head,
   3448                                  uc->tues_tail,
   3449                                  tue);
   3450     tue->uc = uc;
   3451     tue->policies = GNUNET_new (struct PolicyMethodReference);
   3452     *tue->policies = *pmr;
   3453     tue->provider_url = GNUNET_strdup (provider_url);
   3454     tue->am_idx = am_idx;
   3455     tue->policies_length = 1;
   3456     if (GNUNET_OK !=
   3457         ANASTASIS_REDUX_lookup_salt_ (&uc->rs->common,
   3458                                       provider_url,
   3459                                       &provider_salt))
   3460     {
   3461       GNUNET_break (0);
   3462       upload_cancel_cb (uc);
   3463       return GNUNET_SYSERR;
   3464     }
   3465     ANASTASIS_CRYPTO_user_identifier_derive (user_id,
   3466                                              &provider_salt,
   3467                                              &id);
   3468     tue->tu = ANASTASIS_truth_upload (ANASTASIS_REDUX_ctx_,
   3469                                       &id,
   3470                                       provider_url,
   3471                                       auth_method->type,
   3472                                       auth_method->instructions,
   3473                                       auth_method->mime_type,
   3474                                       &provider_salt,
   3475                                       auth_method->challenge,
   3476                                       auth_method->challenge_size,
   3477                                       uc->years,
   3478                                       uc->timeout,
   3479                                       &truth_upload_cb,
   3480                                       tue);
   3481     if (NULL == tue->tu)
   3482     {
   3483       GNUNET_break (0);
   3484       upload_cancel_cb (uc);
   3485       return GNUNET_SYSERR;
   3486     }
   3487     return GNUNET_OK;
   3488   }
   3489 }
   3490 
   3491 
   3492 /**
   3493  * Function to upload truths and recovery document policies.
   3494  * Ultimately transitions to failed state (allowing user to go back
   3495  * and change providers/policies), or payment, or finished.
   3496  *
   3497  * @param state state to operate on
   3498  * @param cb callback (#ANASTASIS_ActionCallback) to call after upload
   3499  * @param cb_cls callback closure
   3500  */
   3501 static struct ANASTASIS_ReduxAction *
   3502 upload (struct ANASTASIS_ReduxState *rs,
   3503         ANASTASIS_ActionCallback cb,
   3504         void *cb_cls)
   3505 {
   3506   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   3507   struct UploadContext *uc;
   3508 
   3509   if (! b->have_expiration)
   3510   {
   3511     ANASTASIS_REDUX_fail_ (rs,
   3512                            cb,
   3513                            cb_cls,
   3514                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3515                            "'expiration' missing");
   3516     return NULL;
   3517   }
   3518   if (0 == b->authentication_methods_len)
   3519   {
   3520     ANASTASIS_REDUX_fail_ (rs,
   3521                            cb,
   3522                            cb_cls,
   3523                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3524                            "'authentication_methods' must be non-empty array");
   3525     return NULL;
   3526   }
   3527   if (0 == b->policies_len)
   3528   {
   3529     ANASTASIS_REDUX_fail_ (rs,
   3530                            cb,
   3531                            cb_cls,
   3532                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3533                            "'policies' must be non-empty array");
   3534     return NULL;
   3535   }
   3536 
   3537   uc = GNUNET_new (struct UploadContext);
   3538   uc->ra.cleanup = &upload_cancel_cb;
   3539   uc->ra.cleanup_cls = uc;
   3540   uc->cb = cb;
   3541   uc->cb_cls = cb_cls;
   3542   uc->rs = rs;
   3543   uc->years = expiration_to_years (b->expiration);
   3544   if (b->have_pay_arguments &&
   3545       b->pay_arguments.have_timeout)
   3546     uc->timeout = b->pay_arguments.timeout;
   3547 
   3548   {
   3549     unsigned int async_truth = 0;
   3550 
   3551     for (unsigned int pindex = 0; pindex < b->policies_len; pindex++)
   3552     {
   3553       const struct ANASTASIS_ReduxPolicy *policy = &b->policies[pindex];
   3554 
   3555       if (0 == policy->methods_len)
   3556       {
   3557         uc_fail (uc,
   3558                  TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3559                  "'policies' must be non-empty array");
   3560         return NULL;
   3561       }
   3562       for (unsigned int mindex = 0; mindex < policy->methods_len; mindex++)
   3563       {
   3564         const struct ANASTASIS_ReduxPolicyMethod *pm
   3565           = &policy->methods[mindex];
   3566         unsigned int am_idx = pm->authentication_method.idx;
   3567         struct PolicyMethodReference pmr = {
   3568           .policy_index = pindex,
   3569           .method_index = mindex
   3570         };
   3571         const struct ANASTASIS_ReduxAuthMethod *amj;
   3572         int ret;
   3573 
   3574         if (am_idx >= b->authentication_methods_len)
   3575         {
   3576           uc_fail (
   3577             uc,
   3578             TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3579             "'authentication_method' refers to invalid authorization index malformed");
   3580           return NULL;
   3581         }
   3582         amj = &b->authentication_methods[am_idx];
   3583         if (NULL == pm->truth)
   3584         {
   3585           ret = check_truth_upload (uc,
   3586                                     &pmr,
   3587                                     pm->provider.url,
   3588                                     am_idx,
   3589                                     amj);
   3590           if (GNUNET_SYSERR == ret)
   3591           {
   3592             /* check_truth_upload() already disposed of @a uc */
   3593             ANASTASIS_redux_fail_ (cb,
   3594                                    cb_cls,
   3595                                    TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3596                                    NULL);
   3597             return NULL;
   3598           }
   3599           if (GNUNET_OK == ret)
   3600             async_truth++;
   3601         }
   3602         else
   3603         {
   3604           ret = add_truth_object (uc,
   3605                                   &pmr,
   3606                                   pm->provider.url,
   3607                                   am_idx,
   3608                                   pm,
   3609                                   &async_truth,
   3610                                   amj);
   3611           if (GNUNET_SYSERR == ret)
   3612           {
   3613             uc_fail (uc,
   3614                      TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3615                      NULL);
   3616             return NULL;
   3617           }
   3618         }
   3619       } /* end for all methods of policy */
   3620     } /* end for all policies */
   3621     if (async_truth > 0)
   3622       return &uc->ra;
   3623   }
   3624   share_secret (uc);
   3625   if (NULL == uc->ss)
   3626     return NULL;
   3627   return &uc->ra;
   3628 }
   3629 
   3630 
   3631 /**
   3632  * Test if the core secret @a secret_size is small enough to be stored
   3633  * at all providers, which have a minimum upload limit of @a min_limit_in_mb.
   3634  *
   3635  * For now, we do not precisely calculate the size of the recovery document,
   3636  * and simply assume that the instructions (i.e. security questions) are all
   3637  * relatively small (aka sane), and that the number of authentication methods
   3638  * and recovery policies is similarly small so that all of this meta data
   3639  * fits in 512 kb (which is VERY big).
   3640  *
   3641  * Even with the minimum permitted upload limit of 1 MB (which is likely,
   3642  * given that there is hardly a reason for providers to offer more), this
   3643  * leaves 512 kb for the @a secret_size, which should be plenty (given
   3644  * that this is supposed to be for a master key, and not the actual data).
   3645  *
   3646  * @param rs our state, could be used in the future to calculate the
   3647  *        size of the recovery document without the core secret
   3648  * @param secret_size size of the core secret
   3649  * @param min_limit_in_mb minimum upload size of all providers
   3650  */
   3651 static bool
   3652 core_secret_fits (const struct ANASTASIS_ReduxState *rs,
   3653                   size_t secret_size,
   3654                   uint32_t min_limit_in_mb)
   3655 {
   3656   (void) rs;
   3657   return (min_limit_in_mb * 1024LL * 1024LL >
   3658           512LLU * 1024LLU + secret_size);
   3659 }
   3660 
   3661 
   3662 /**
   3663  * Check if the upload size limit is satisfied.
   3664  *
   3665  * @param rs our state
   3666  * @param jsecret the uploaded secret
   3667  * @return #GNUNET_OK if @a secret_size works for all providers,
   3668  *     #GNUNET_NO if the @a secret_size is too big,
   3669  *     #GNUNET_SYSERR if a provider has a limit of 0
   3670  */
   3671 static enum GNUNET_GenericReturnValue
   3672 check_upload_size_limit (const struct ANASTASIS_ReduxState *rs,
   3673                          const json_t *jsecret)
   3674 {
   3675   uint32_t min_limit = UINT32_MAX;
   3676   size_t secret_size;
   3677 
   3678   {
   3679     char *secret;
   3680 
   3681     secret = json_dumps (jsecret,
   3682                          JSON_COMPACT | JSON_SORT_KEYS);
   3683     GNUNET_assert (NULL != secret);
   3684     secret_size = strlen (secret);
   3685     GNUNET_free (secret);
   3686   }
   3687 
   3688   /* We calculate the minimum upload limit of all possible providers;
   3689      this is under the (simplified) assumption that we store the
   3690      recovery document at all providers; this may be changed later,
   3691      see #6760. */
   3692   for (unsigned int i = 0; i < rs->common.providers_len; i++)
   3693   {
   3694     const struct ANASTASIS_ReduxProvider *p = &rs->common.providers[i];
   3695 
   3696     if ( (ANASTASIS_RPS_OK != p->status) ||
   3697          (! p->have_config) ||
   3698          (MHD_HTTP_OK != p->config.http_status) )
   3699       continue;
   3700     if (0 == p->config.storage_limit_in_megabytes)
   3701       return GNUNET_SYSERR;
   3702     min_limit = GNUNET_MIN (min_limit,
   3703                             p->config.storage_limit_in_megabytes);
   3704   }
   3705   if (! core_secret_fits (rs,
   3706                           secret_size,
   3707                           min_limit))
   3708     return GNUNET_NO;
   3709   return GNUNET_OK;
   3710 }
   3711 
   3712 
   3713 /**
   3714  * DispatchHandler/Callback function which is called for a
   3715  * "enter_secret" action.
   3716  *
   3717  * @param state state to operate on
   3718  * @param arguments arguments to use for operation on state
   3719  * @param cb callback to call during/after operation
   3720  * @param cb_cls callback closure
   3721  * @return NULL
   3722  */
   3723 static struct ANASTASIS_ReduxAction *
   3724 enter_secret (struct ANASTASIS_ReduxState *rs,
   3725               const json_t *arguments,
   3726               ANASTASIS_ActionCallback cb,
   3727               void *cb_cls)
   3728 {
   3729   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   3730   const json_t *jsecret;
   3731   struct GNUNET_TIME_Timestamp expiration
   3732     = GNUNET_TIME_UNIT_ZERO_TS;
   3733   struct GNUNET_JSON_Specification spec[] = {
   3734     GNUNET_JSON_spec_object_const ("secret",
   3735                                    &jsecret),
   3736     GNUNET_JSON_spec_mark_optional (
   3737       GNUNET_JSON_spec_timestamp ("expiration",
   3738                                   &expiration),
   3739       NULL),
   3740     GNUNET_JSON_spec_end ()
   3741   };
   3742 
   3743   if (NULL == arguments)
   3744   {
   3745     ANASTASIS_REDUX_fail_ (rs,
   3746                            cb,
   3747                            cb_cls,
   3748                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3749                            "arguments missing");
   3750     return NULL;
   3751   }
   3752   if (GNUNET_OK !=
   3753       GNUNET_JSON_parse (arguments,
   3754                          spec,
   3755                          NULL, NULL))
   3756   {
   3757     ANASTASIS_REDUX_fail_ (rs,
   3758                            cb,
   3759                            cb_cls,
   3760                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3761                            "'secret' argument required");
   3762     return NULL;
   3763   }
   3764 
   3765   /* check upload size limit */
   3766   switch (check_upload_size_limit (rs,
   3767                                    jsecret))
   3768   {
   3769   case GNUNET_SYSERR:
   3770     ANASTASIS_REDUX_fail_ (rs,
   3771                            cb,
   3772                            cb_cls,
   3773                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3774                            "provider has an upload limit of 0");
   3775     return NULL;
   3776   case GNUNET_NO:
   3777     ANASTASIS_REDUX_fail_ (rs,
   3778                            cb,
   3779                            cb_cls,
   3780                            TALER_EC_ANASTASIS_REDUCER_SECRET_TOO_BIG,
   3781                            NULL);
   3782     return NULL;
   3783   default:
   3784     break;
   3785   }
   3786   if (! GNUNET_TIME_absolute_is_zero (expiration.abs_time))
   3787   {
   3788     if (GNUNET_OK !=
   3789         update_expiration_cost (rs,
   3790                                 expiration))
   3791     {
   3792       ANASTASIS_REDUX_fail_ (rs,
   3793                              cb,
   3794                              cb_cls,
   3795                              TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
   3796                              "could not calculate expiration cost");
   3797       return NULL;
   3798     }
   3799   }
   3800   json_decref (b->core_secret);
   3801   b->core_secret = json_incref ((json_t *) jsecret);
   3802   ANASTASIS_REDUX_return_ (rs,
   3803                            cb,
   3804                            cb_cls,
   3805                            TALER_EC_NONE);
   3806   return NULL;
   3807 }
   3808 
   3809 
   3810 /**
   3811  * DispatchHandler/Callback function which is called for a
   3812  * "clear_secret" action.
   3813  *
   3814  * @param state state to operate on
   3815  * @param arguments arguments to use for operation on state
   3816  * @param cb callback to call during/after operation
   3817  * @param cb_cls callback closure
   3818  * @return NULL
   3819  */
   3820 static struct ANASTASIS_ReduxAction *
   3821 clear_secret (struct ANASTASIS_ReduxState *rs,
   3822               const json_t *arguments,
   3823               ANASTASIS_ActionCallback cb,
   3824               void *cb_cls)
   3825 {
   3826   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   3827 
   3828   if (NULL == b->core_secret)
   3829   {
   3830     ANASTASIS_REDUX_fail_ (rs,
   3831                            cb,
   3832                            cb_cls,
   3833                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3834                            "'core_secret' not set");
   3835     return NULL;
   3836   }
   3837   json_decref (b->core_secret);
   3838   b->core_secret = NULL;
   3839   ANASTASIS_REDUX_return_ (rs,
   3840                            cb,
   3841                            cb_cls,
   3842                            TALER_EC_NONE);
   3843   return NULL;
   3844 }
   3845 
   3846 
   3847 /**
   3848  * DispatchHandler/Callback function which is called for an
   3849  * "enter_secret_name" action.
   3850  *
   3851  * @param state state to operate on
   3852  * @param arguments arguments to use for operation on state
   3853  * @param cb callback to call during/after operation
   3854  * @param cb_cls callback closure
   3855  * @return NULL
   3856  */
   3857 static struct ANASTASIS_ReduxAction *
   3858 enter_secret_name (struct ANASTASIS_ReduxState *rs,
   3859                    const json_t *arguments,
   3860                    ANASTASIS_ActionCallback cb,
   3861                    void *cb_cls)
   3862 {
   3863   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   3864   const char *secret_name = NULL;
   3865   struct GNUNET_JSON_Specification spec[] = {
   3866     GNUNET_JSON_spec_string ("name",
   3867                              &secret_name),
   3868     GNUNET_JSON_spec_end ()
   3869   };
   3870 
   3871   if (NULL == arguments)
   3872   {
   3873     ANASTASIS_REDUX_fail_ (rs,
   3874                            cb,
   3875                            cb_cls,
   3876                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3877                            "arguments missing");
   3878     return NULL;
   3879   }
   3880   if (GNUNET_OK !=
   3881       GNUNET_JSON_parse (arguments,
   3882                          spec,
   3883                          NULL, NULL))
   3884   {
   3885     ANASTASIS_REDUX_fail_ (rs,
   3886                            cb,
   3887                            cb_cls,
   3888                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3889                            "'name' argument required");
   3890     return NULL;
   3891   }
   3892   GNUNET_free (b->secret_name);
   3893   b->secret_name = GNUNET_strdup (secret_name);
   3894   ANASTASIS_REDUX_return_ (rs,
   3895                            cb,
   3896                            cb_cls,
   3897                            TALER_EC_NONE);
   3898   return NULL;
   3899 }
   3900 
   3901 
   3902 /**
   3903  * DispatchHandler/Callback function which is called for the
   3904  * "update_expiration" action in the "secret editing" state.
   3905  * Updates how long we are to store the truth and policies
   3906  * and computes the new cost.
   3907  *
   3908  * @param state state to operate on
   3909  * @param arguments arguments to use for operation on state
   3910  * @param cb callback to call during/after operation
   3911  * @param cb_cls callback closure
   3912  * @return NULL (synchronous operation)
   3913  */
   3914 static struct ANASTASIS_ReduxAction *
   3915 update_expiration (struct ANASTASIS_ReduxState *rs,
   3916                    const json_t *arguments,
   3917                    ANASTASIS_ActionCallback cb,
   3918                    void *cb_cls)
   3919 {
   3920   struct GNUNET_TIME_Timestamp expiration;
   3921   struct GNUNET_JSON_Specification spec[] = {
   3922     GNUNET_JSON_spec_timestamp ("expiration",
   3923                                 &expiration),
   3924     GNUNET_JSON_spec_end ()
   3925   };
   3926 
   3927   if (NULL == arguments)
   3928   {
   3929     GNUNET_break (0);
   3930     ANASTASIS_REDUX_fail_ (rs,
   3931                            cb,
   3932                            cb_cls,
   3933                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3934                            "arguments missing");
   3935     return NULL;
   3936   }
   3937   if (GNUNET_OK !=
   3938       GNUNET_JSON_parse (arguments,
   3939                          spec,
   3940                          NULL, NULL))
   3941   {
   3942     GNUNET_break (0);
   3943     ANASTASIS_REDUX_fail_ (rs,
   3944                            cb,
   3945                            cb_cls,
   3946                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   3947                            "'expiration' argument required");
   3948     return NULL;
   3949   }
   3950   if (GNUNET_OK !=
   3951       update_expiration_cost (rs,
   3952                               expiration))
   3953   {
   3954     GNUNET_break (0);
   3955     ANASTASIS_REDUX_fail_ (rs,
   3956                            cb,
   3957                            cb_cls,
   3958                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID_FOR_STATE,
   3959                            "could not calculate expiration cost");
   3960     return NULL;
   3961   }
   3962   ANASTASIS_REDUX_return_ (rs,
   3963                            cb,
   3964                            cb_cls,
   3965                            TALER_EC_NONE);
   3966   return NULL;
   3967 }
   3968 
   3969 
   3970 /**
   3971  * DispatchHandler/Callback function which is called for the
   3972  * "next" action in the "secret editing" state.
   3973  * Returns an #ANASTASIS_ReduxAction as operation is async.
   3974  *
   3975  * @param state state to operate on
   3976  * @param arguments arguments to use for operation on state
   3977  * @param cb callback to call during/after operation
   3978  * @param cb_cls callback closure
   3979  */
   3980 static struct ANASTASIS_ReduxAction *
   3981 finish_secret (struct ANASTASIS_ReduxState *rs,
   3982                const json_t *arguments,
   3983                ANASTASIS_ActionCallback cb,
   3984                void *cb_cls)
   3985 {
   3986   const struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   3987 
   3988   if (NULL == b->core_secret)
   3989   {
   3990     ANASTASIS_REDUX_fail_ (rs,
   3991                            cb,
   3992                            cb_cls,
   3993                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   3994                            "State parsing failed: 'core_secret' is missing");
   3995     return NULL;
   3996   }
   3997 
   3998   /* check upload size limit */
   3999   switch (check_upload_size_limit (rs,
   4000                                    b->core_secret))
   4001   {
   4002   case GNUNET_SYSERR:
   4003     ANASTASIS_REDUX_fail_ (rs,
   4004                            cb,
   4005                            cb_cls,
   4006                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   4007                            "provider has an upload limit of 0");
   4008     return NULL;
   4009   case GNUNET_NO:
   4010     ANASTASIS_REDUX_fail_ (rs,
   4011                            cb,
   4012                            cb_cls,
   4013                            TALER_EC_ANASTASIS_REDUCER_SECRET_TOO_BIG,
   4014                            NULL);
   4015     return NULL;
   4016   default:
   4017     break;
   4018   }
   4019   return upload (rs,
   4020                  cb,
   4021                  cb_cls);
   4022 }
   4023 
   4024 
   4025 /**
   4026  * Remember the arguments of a "pay" action in @a rs, so that they are
   4027  * still around when the upload is retried after the payment.
   4028  *
   4029  * @param[in,out] rs state to update
   4030  * @param arguments arguments of the action, may be NULL
   4031  * @param cb callback to report a failure to
   4032  * @param cb_cls closure for @a cb
   4033  * @return false if @a arguments were malformed, in which case @a cb has
   4034  *         been invoked and @a rs freed
   4035  */
   4036 static bool
   4037 set_pay_arguments (struct ANASTASIS_ReduxState *rs,
   4038                    const json_t *arguments,
   4039                    ANASTASIS_ActionCallback cb,
   4040                    void *cb_cls)
   4041 {
   4042   struct ANASTASIS_ReduxBackup *b = &rs->details.backup;
   4043   bool no_timeout;
   4044   struct GNUNET_JSON_Specification spec[] = {
   4045     GNUNET_JSON_spec_mark_optional (
   4046       GNUNET_JSON_spec_relative_time ("timeout",
   4047                                       &b->pay_arguments.timeout),
   4048       &no_timeout),
   4049     GNUNET_JSON_spec_end ()
   4050   };
   4051 
   4052   if (NULL == arguments)
   4053     return true;
   4054   if (GNUNET_OK !=
   4055       GNUNET_JSON_parse (arguments,
   4056                          spec,
   4057                          NULL, NULL))
   4058   {
   4059     json_dumpf ((json_t *) arguments,
   4060                 stderr,
   4061                 JSON_INDENT (2));
   4062     GNUNET_break (0);
   4063     ANASTASIS_REDUX_fail_ (rs,
   4064                            cb,
   4065                            cb_cls,
   4066                            TALER_EC_ANASTASIS_REDUCER_INPUT_INVALID,
   4067                            "'timeout' must be valid delay");
   4068     return false;
   4069   }
   4070   b->have_pay_arguments = true;
   4071   b->pay_arguments.have_timeout = ! no_timeout;
   4072   return true;
   4073 }
   4074 
   4075 
   4076 /**
   4077  * DispatchHandler/Callback function which is called for a
   4078  * "pay" action.
   4079  * Returns an #ANASTASIS_ReduxAction as operation is async.
   4080  *
   4081  * @param[in] rs state to operate on
   4082  * @param arguments arguments to use for operation on state
   4083  * @param cb callback to call during/after operation
   4084  * @param cb_cls callback closure
   4085  */
   4086 static struct ANASTASIS_ReduxAction *
   4087 pay_truths_backup (struct ANASTASIS_ReduxState *rs,
   4088                    const json_t *arguments,
   4089                    ANASTASIS_ActionCallback cb,
   4090                    void *cb_cls)
   4091 {
   4092   /* Clear 'payments' if it exists */
   4093   ANASTASIS_REDUX_payments_clear_ (&rs->details.backup);
   4094   if (! set_pay_arguments (rs,
   4095                            arguments,
   4096                            cb,
   4097                            cb_cls))
   4098     return NULL;
   4099   return upload (rs,
   4100                  cb,
   4101                  cb_cls);
   4102 }
   4103 
   4104 
   4105 /**
   4106  * DispatchHandler/Callback function which is called for a
   4107  * "pay" action.
   4108  * Returns an #ANASTASIS_ReduxAction as operation is async.
   4109  *
   4110  * @param state state to operate on
   4111  * @param arguments arguments to use for operation on state
   4112  * @param cb callback to call during/after operation
   4113  * @param cb_cls callback closure
   4114  */
   4115 static struct ANASTASIS_ReduxAction *
   4116 pay_policies_backup (struct ANASTASIS_ReduxState *rs,
   4117                      const json_t *arguments,
   4118                      ANASTASIS_ActionCallback cb,
   4119                      void *cb_cls)
   4120 {
   4121   /* Clear 'policy_payment_requests' if it exists */
   4122   ANASTASIS_REDUX_policy_payment_requests_clear_ (&rs->details.backup);
   4123   if (! set_pay_arguments (rs,
   4124                            arguments,
   4125                            cb,
   4126                            cb_cls))
   4127     return NULL;
   4128   return upload (rs,
   4129                  cb,
   4130                  cb_cls);
   4131 }
   4132 
   4133 
   4134 /**
   4135  * DispatchHandler/Callback function which is called for a
   4136  * "back" action if state is "FINISHED".
   4137  *
   4138  * @param state state to operate on
   4139  * @param arguments arguments to use for operation on state
   4140  * @param cb callback to call during/after operation
   4141  * @param cb_cls callback closure
   4142  * @return NULL
   4143  */
   4144 static struct ANASTASIS_ReduxAction *
   4145 back_finished (struct ANASTASIS_ReduxState *rs,
   4146                const json_t *arguments,
   4147                ANASTASIS_ActionCallback cb,
   4148                void *cb_cls)
   4149 {
   4150   set_state (rs,
   4151              ANASTASIS_BACKUP_STATE_SECRET_EDITING);
   4152   ANASTASIS_REDUX_return_ (rs,
   4153                            cb,
   4154                            cb_cls,
   4155                            TALER_EC_NONE);
   4156   return NULL;
   4157 }
   4158 
   4159 
   4160 /**
   4161  * Signature of callback function that implements a state transition.
   4162  *
   4163  *  @param[in] rs current state
   4164  *  @param arguments arguments for the state transition
   4165  *  @param cb function to call when done
   4166  *  @param cb_cls closure for @a cb
   4167  */
   4168 typedef struct ANASTASIS_ReduxAction *
   4169 (*DispatchHandler)(struct ANASTASIS_ReduxState *rs,
   4170                    const json_t *arguments,
   4171                    ANASTASIS_ActionCallback cb,
   4172                    void *cb_cls);
   4173 
   4174 
   4175 struct ANASTASIS_ReduxAction *
   4176 ANASTASIS_backup_action_ (struct ANASTASIS_ReduxState *rs,
   4177                           const char *action,
   4178                           const json_t *arguments,
   4179                           ANASTASIS_ActionCallback cb,
   4180                           void *cb_cls)
   4181 {
   4182   struct Dispatcher
   4183   {
   4184     enum ANASTASIS_BackupState backup_state;
   4185     const char *backup_action;
   4186     DispatchHandler fun;
   4187   } dispatchers[] = {
   4188     {
   4189       ANASTASIS_BACKUP_STATE_AUTHENTICATIONS_EDITING,
   4190       "add_authentication",
   4191       &add_authentication
   4192     },
   4193     {
   4194       ANASTASIS_BACKUP_STATE_AUTHENTICATIONS_EDITING,
   4195       "delete_authentication",
   4196       &del_authentication
   4197     },
   4198     {
   4199       ANASTASIS_BACKUP_STATE_AUTHENTICATIONS_EDITING,
   4200       "next",
   4201       &done_authentication
   4202     },
   4203     {
   4204       ANASTASIS_BACKUP_STATE_AUTHENTICATIONS_EDITING,
   4205       "add_provider",
   4206       &add_provider
   4207     },
   4208     {
   4209       ANASTASIS_BACKUP_STATE_AUTHENTICATIONS_EDITING,
   4210       "poll_providers",
   4211       &ANASTASIS_REDUX_poll_providers_
   4212     },
   4213     {
   4214       ANASTASIS_BACKUP_STATE_AUTHENTICATIONS_EDITING,
   4215       "back",
   4216       &ANASTASIS_back_generic_decrement_
   4217     },
   4218     {
   4219       ANASTASIS_BACKUP_STATE_POLICIES_REVIEWING,
   4220       "add_policy",
   4221       &add_policy
   4222     },
   4223     {
   4224       ANASTASIS_BACKUP_STATE_POLICIES_REVIEWING,
   4225       "update_policy",
   4226       &update_policy
   4227     },
   4228     {
   4229       ANASTASIS_BACKUP_STATE_POLICIES_REVIEWING,
   4230       "delete_policy",
   4231       &del_policy
   4232     },
   4233     {
   4234       ANASTASIS_BACKUP_STATE_POLICIES_REVIEWING,
   4235       "delete_challenge",
   4236       &del_challenge
   4237     },
   4238     {
   4239       ANASTASIS_BACKUP_STATE_POLICIES_REVIEWING,
   4240       "next",
   4241       &done_policy_review
   4242     },
   4243     {
   4244       ANASTASIS_BACKUP_STATE_POLICIES_REVIEWING,
   4245       "back",
   4246       &ANASTASIS_back_generic_decrement_
   4247     },
   4248     {
   4249       ANASTASIS_BACKUP_STATE_SECRET_EDITING,
   4250       "enter_secret",
   4251       &enter_secret
   4252     },
   4253     {
   4254       ANASTASIS_BACKUP_STATE_SECRET_EDITING,
   4255       "clear_secret",
   4256       &clear_secret
   4257     },
   4258     {
   4259       ANASTASIS_BACKUP_STATE_SECRET_EDITING,
   4260       "enter_secret_name",
   4261       &enter_secret_name
   4262     },
   4263     {
   4264       ANASTASIS_BACKUP_STATE_SECRET_EDITING,
   4265       "back",
   4266       &ANASTASIS_back_generic_decrement_
   4267     },
   4268     {
   4269       ANASTASIS_BACKUP_STATE_SECRET_EDITING,
   4270       "update_expiration",
   4271       &update_expiration
   4272     },
   4273     {
   4274       ANASTASIS_BACKUP_STATE_SECRET_EDITING,
   4275       "next",
   4276       &finish_secret
   4277     },
   4278     {
   4279       ANASTASIS_BACKUP_STATE_TRUTHS_PAYING,
   4280       "pay",
   4281       &pay_truths_backup
   4282     },
   4283     {
   4284       ANASTASIS_BACKUP_STATE_POLICIES_PAYING,
   4285       "pay",
   4286       &pay_policies_backup
   4287     },
   4288     {
   4289       ANASTASIS_BACKUP_STATE_BACKUP_FINISHED,
   4290       "back",
   4291       &back_finished
   4292     },
   4293     { ANASTASIS_BACKUP_STATE_INVALID, NULL, NULL }
   4294   };
   4295   enum ANASTASIS_BackupState bs = rs->details.backup.state;
   4296 
   4297   GNUNET_assert (ANASTASIS_RT_BACKUP == rs->type);
   4298   for (unsigned int i = 0; NULL != dispatchers[i].fun; i++)
   4299   {
   4300     if ( (bs == dispatchers[i].backup_state) &&
   4301          (0 == strcmp (action,
   4302                        dispatchers[i].backup_action)) )
   4303     {
   4304       return dispatchers[i].fun (rs,
   4305                                  arguments,
   4306                                  cb,
   4307                                  cb_cls);
   4308     }
   4309   }
   4310   ANASTASIS_REDUX_fail_ (rs,
   4311                          cb,
   4312                          cb_cls,
   4313                          TALER_EC_ANASTASIS_REDUCER_ACTION_INVALID,
   4314                          action);
   4315   return NULL;
   4316 }
   4317 
   4318 
   4319 /**
   4320  * State for a #ANASTASIS_REDUX_backup_begin_() operation.
   4321  */
   4322 struct BackupStartState;
   4323 
   4324 
   4325 /**
   4326  * Entry in the list of all known applicable Anastasis providers.
   4327  * Used to wait for it to complete downloading /config.
   4328  */
   4329 struct BackupStartStateProviderEntry
   4330 {
   4331   /**
   4332    * Kept in a DLL.
   4333    */
   4334   struct BackupStartStateProviderEntry *next;
   4335 
   4336   /**
   4337    * Kept in a DLL.
   4338    */
   4339   struct BackupStartStateProviderEntry *prev;
   4340 
   4341   /**
   4342    * Main operation this entry is part of.
   4343    */
   4344   struct BackupStartState *bss;
   4345 
   4346   /**
   4347    * Ongoing reducer action to obtain /config, NULL if completed.
   4348    */
   4349   struct ANASTASIS_ReduxAction *ra;
   4350 
   4351   /**
   4352    * Final result of the operation (once completed).
   4353    */
   4354   enum TALER_ErrorCode ec;
   4355 };
   4356 
   4357 
   4358 struct BackupStartState
   4359 {
   4360   /**
   4361    * Head of list of provider /config operations we are doing.
   4362    */
   4363   struct BackupStartStateProviderEntry *pe_head;
   4364 
   4365   /**
   4366    * Tail of list of provider /config operations we are doing.
   4367    */
   4368   struct BackupStartStateProviderEntry *pe_tail;
   4369 
   4370   /**
   4371    * State we are updating; we own it.  All our entries update it in
   4372    * place, so there is nothing to merge once they are done.
   4373    */
   4374   struct ANASTASIS_ReduxState *rs;
   4375 
   4376   /**
   4377    * Function to call when we are done.
   4378    */
   4379   ANASTASIS_ActionCallback cb;
   4380 
   4381   /**
   4382    * Closure for @e cb.
   4383    */
   4384   void *cb_cls;
   4385 
   4386   /**
   4387    * Redux action we returned to our controller.
   4388    */
   4389   struct ANASTASIS_ReduxAction ra;
   4390 
   4391   /**
   4392    * Number of provider /config operations in @e ba_head that
   4393    * are still awaiting completion.
   4394    */
   4395   unsigned int pending;
   4396 };
   4397 
   4398 
   4399 /**
   4400  * The backup start operation is being aborted, terminate.
   4401  *
   4402  * @param cls a `struct BackupStartState *`
   4403  */
   4404 static void
   4405 abort_backup_begin_cb (void *cls)
   4406 {
   4407   struct BackupStartState *bss = cls;
   4408   struct BackupStartStateProviderEntry *pe;
   4409 
   4410   while (NULL != (pe = bss->pe_head))
   4411   {
   4412     GNUNET_CONTAINER_DLL_remove (bss->pe_head,
   4413                                  bss->pe_tail,
   4414                                  pe);
   4415     if (NULL != pe->ra)
   4416       pe->ra->cleanup (pe->ra->cleanup_cls);
   4417     GNUNET_free (pe);
   4418   }
   4419   ANASTASIS_REDUX_state_free_ (bss->rs);
   4420   GNUNET_free (bss);
   4421 }
   4422 
   4423 
   4424 /**
   4425  * We finished downloading /config from all providers, trigger the
   4426  * continuation and free our state.
   4427  *
   4428  * @param[in] bss main state to return
   4429  */
   4430 static void
   4431 providers_complete (struct BackupStartState *bss)
   4432 {
   4433   struct ANASTASIS_ReduxState *rs = bss->rs;
   4434   ANASTASIS_ActionCallback cb = bss->cb;
   4435   void *cb_cls = bss->cb_cls;
   4436 
   4437   bss->rs = NULL;
   4438   abort_backup_begin_cb (bss);
   4439   ANASTASIS_REDUX_return_ (rs,
   4440                            cb,
   4441                            cb_cls,
   4442                            TALER_EC_NONE);
   4443 }
   4444 
   4445 
   4446 /**
   4447  * Function called when the complete information about a provider
   4448  * was added to the state.
   4449  *
   4450  * @param cls a `struct BackupStartStateProviderEntry`
   4451  * @param error error code
   4452  * @param rs the state, updated in place
   4453  */
   4454 static void
   4455 provider_added_cb (void *cls,
   4456                    enum TALER_ErrorCode error,
   4457                    struct ANASTASIS_ReduxState *rs)
   4458 {
   4459   struct BackupStartStateProviderEntry *pe = cls;
   4460   struct BackupStartState *bss = pe->bss;
   4461 
   4462   GNUNET_assert (rs == bss->rs);
   4463   /* our waiter unlinks and frees itself right after this call */
   4464   pe->ra = NULL;
   4465   GNUNET_CONTAINER_DLL_remove (bss->pe_head,
   4466                                bss->pe_tail,
   4467                                pe);
   4468   pe->ec = error;
   4469   GNUNET_free (pe);
   4470   bss->pending--;
   4471   if (0 == bss->pending)
   4472     providers_complete (bss);
   4473 }
   4474 
   4475 
   4476 struct ANASTASIS_ReduxAction *
   4477 ANASTASIS_REDUX_backup_begin_ (struct ANASTASIS_ReduxState *rs,
   4478                                const json_t *arguments,
   4479                                ANASTASIS_ActionCallback cb,
   4480                                void *cb_cls)
   4481 {
   4482   struct BackupStartState *bss;
   4483 
   4484   if (! rs->common.have_providers)
   4485   {
   4486     GNUNET_break (0);
   4487     ANASTASIS_REDUX_fail_ (rs,
   4488                            cb,
   4489                            cb_cls,
   4490                            TALER_EC_ANASTASIS_REDUCER_STATE_INVALID,
   4491                            "'authentication_providers' missing");
   4492     return NULL;
   4493   }
   4494   bss = GNUNET_new (struct BackupStartState);
   4495   bss->rs = rs;
   4496   bss->cb = cb;
   4497   bss->cb_cls = cb_cls;
   4498   bss->ra.cleanup_cls = bss;
   4499   bss->ra.cleanup = &abort_backup_begin_cb;
   4500   bss->pending = 1; /* decremented after initialization loop */
   4501 
   4502   {
   4503     /* The /config replies add providers to the state, so take a
   4504        snapshot of the URLs to query before starting any of them. */
   4505     unsigned int len = rs->common.providers_len;
   4506     char *urls[GNUNET_NZL (len)];
   4507 
   4508     for (unsigned int i = 0; i < len; i++)
   4509       urls[i] = (ANASTASIS_RPS_DISABLED == rs->common.providers[i].status)
   4510                 ? NULL
   4511                 : GNUNET_strdup (rs->common.providers[i].url.url);
   4512     for (unsigned int i = 0; i < len; i++)
   4513     {
   4514       struct BackupStartStateProviderEntry *pe;
   4515 
   4516       if (NULL == urls[i])
   4517         continue;
   4518       pe = GNUNET_new (struct BackupStartStateProviderEntry);
   4519       pe->bss = bss;
   4520       GNUNET_CONTAINER_DLL_insert (bss->pe_head,
   4521                                    bss->pe_tail,
   4522                                    pe);
   4523       bss->pending++;
   4524       pe->ra = ANASTASIS_REDUX_add_provider_to_state_ (urls[i],
   4525                                                        rs,
   4526                                                        &provider_added_cb,
   4527                                                        pe);
   4528       GNUNET_assert (NULL != pe->ra);
   4529     }
   4530     for (unsigned int i = 0; i < len; i++)
   4531       GNUNET_free (urls[i]);
   4532   }
   4533   bss->pending--;
   4534   if (0 == bss->pending)
   4535   {
   4536     providers_complete (bss);
   4537     return NULL;
   4538   }
   4539   return &bss->ra;
   4540 }