aboutsummaryrefslogtreecommitdiff
path: root/src/backend/taler-merchant-httpd_post-orders-ID-abort.c
blob: 4f6b8667a0ebda6fc145912dd58677c5be0ab135 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
/*
  This file is part of TALER
  (C) 2014-2020 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as
  published by the Free Software Foundation; either version 3,
  or (at your option) any later version.

  TALER is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public
  License along with TALER; see the file COPYING.  If not,
  see <http://www.gnu.org/licenses/>
*/
/**
 * @file taler-merchant-httpd_post-orders-ID-abort.c
 * @brief handling of POST /orders/$ID/abort requests
 * @author Marcello Stanisci
 * @author Christian Grothoff
 * @author Florian Dold
 */
#include "platform.h"
#include <taler/taler_json_lib.h>
#include <taler/taler_exchange_service.h>
#include "taler-merchant-httpd_exchanges.h"


/**
 * How long to wait before giving up processing with the exchange?
 */
#define ABORT_GENERIC_TIMEOUT (GNUNET_TIME_relative_multiply ( \
                                 GNUNET_TIME_UNIT_SECONDS, \
                                 30))

/**
 * How often do we retry the (complex!) database transaction?
 */
#define MAX_RETRIES 5

/**
 * Information we keep for an individual call to the /abort handler.
 */
struct AbortContext;

/**
 * Information kept during a /abort request for each coin.
 */
struct RefundDetails
{

  /**
   * Public key of the coin.
   */
  struct TALER_CoinSpendPublicKeyP coin_pub;

  /**
   * Signature from the exchange confirming the refund.
   * Set if we were successful (status 200).
   */
  struct TALER_ExchangeSignatureP exchange_sig;

  /**
   * Public key used for @e exchange_sig.
   * Set if we were successful (status 200).
   */
  struct TALER_ExchangePublicKeyP exchange_pub;

  /**
   * Reference to the main AbortContext
   */
  struct AbortContext *ac;

  /**
   * Handle to the refund operation we are performing for
   * this coin, NULL after the operation is done.
   */
  struct TALER_EXCHANGE_RefundHandle *rh;

  /**
   * URL of the exchange that issued this coin.
   */
  char *exchange_url;

  /**
   * Body of the response from the exchange.  Note that the body returned MUST
   * be freed (if non-NULL).
   */
  json_t *exchange_reply;

  /**
   * Amount this coin contributes to the total purchase price.
   * This amount includes the deposit fee.
   */
  struct TALER_Amount amount_with_fee;

  /**
   * Offset of this coin into the `rd` array of all coins in the
   * @e ac.
   */
  unsigned int index;

  /**
   * HTTP status returned by the exchange (if any).
   */
  unsigned int http_status;

  /**
   * Did we try to process this refund yet?
   */
  bool processed;

};


/**
 * Information we keep for an individual call to the /abort handler.
 */
struct AbortContext
{

  /**
   * Hashed contract terms (according to client).
   */
  struct GNUNET_HashCode h_contract_terms;

  /**
   * Context for our operation.
   */
  struct TMH_HandlerContext *hc;

  /**
   * Stored in a DLL.
   */
  struct AbortContext *next;

  /**
   * Stored in a DLL.
   */
  struct AbortContext *prev;

  /**
   * Array with @e coins_cnt coins we are despositing.
   */
  struct RefundDetails *rd;

  /**
   * MHD connection to return to
   */
  struct MHD_Connection *connection;

  /**
   * Task called when the (suspended) processing for
   * the /abort request times out.
   * Happens when we don't get a response from the exchange.
   */
  struct GNUNET_SCHEDULER_Task *timeout_task;

  /**
   * Response to return, NULL if we don't have one yet.
   */
  struct MHD_Response *response;

  /**
   * Handle to the exchange that we are doing the abortment with.
   * (initially NULL while @e fo is trying to find a exchange).
   */
  struct TALER_EXCHANGE_Handle *mh;

  /**
   * Handle for operation to lookup /keys (and auditors) from
   * the exchange used for this transaction; NULL if no operation is
   * pending.
   */
  struct TMH_EXCHANGES_FindOperation *fo;

  /**
   * URL of the exchange used for the last @e fo.
   */
  const char *current_exchange;

  /**
   * Number of coins this abort is for.  Length of the @e rd array.
   */
  unsigned int coins_cnt;

  /**
   * How often have we retried the 'main' transaction?
   */
  unsigned int retry_counter;

  /**
   * Number of transactions still pending.  Initially set to
   * @e coins_cnt, decremented on each transaction that
   * successfully finished.
   */
  unsigned int pending;

  /**
   * Number of transactions still pending for the currently selected
   * exchange.  Initially set to the number of coins started at the
   * exchange, decremented on each transaction that successfully
   * finished.  Once it hits zero, we pick the next exchange.
   */
  unsigned int pending_at_ce;

  /**
   * HTTP status code to use for the reply, i.e 200 for "OK".
   * Special value UINT_MAX is used to indicate hard errors
   * (no reply, return #MHD_NO).
   */
  unsigned int response_code;

  /**
   * #GNUNET_NO if the @e connection was not suspended,
   * #GNUNET_YES if the @e connection was suspended,
   * #GNUNET_SYSERR if @e connection was resumed to as
   * part of #MH_force_ac_resume during shutdown.
   */
  int suspended;

};


/**
 * Head of active abort context DLL.
 */
static struct AbortContext *ac_head;

/**
 * Tail of active abort context DLL.
 */
static struct AbortContext *ac_tail;


/**
 * Abort all pending /deposit operations.
 *
 * @param ac abort context to abort
 */
static void
abort_refunds (struct AbortContext *ac)
{
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Aborting pending /deposit operations\n");
  for (unsigned int i = 0; i<ac->coins_cnt; i++)
  {
    struct RefundDetails *rdi = &ac->rd[i];

    if (NULL != rdi->rh)
    {
      TALER_EXCHANGE_refund_cancel (rdi->rh);
      rdi->rh = NULL;
    }
  }
}


void
TMH_force_ac_resume ()
{
  for (struct AbortContext *ac = ac_head;
       NULL != ac;
       ac = ac->next)
  {
    abort_refunds (ac);
    if (NULL != ac->timeout_task)
    {
      GNUNET_SCHEDULER_cancel (ac->timeout_task);
      ac->timeout_task = NULL;
    }
    if (GNUNET_YES == ac->suspended)
    {
      ac->suspended = GNUNET_SYSERR;
      MHD_resume_connection (ac->connection);
    }
  }
}


/**
 * Resume the given abort context and send the given response.
 * Stores the response in the @a ac and signals MHD to resume
 * the connection.  Also ensures MHD runs immediately.
 *
 * @param ac abortment context
 * @param response_code response code to use
 * @param response response data to send back
 */
static void
resume_abort_with_response (struct AbortContext *ac,
                            unsigned int response_code,
                            struct MHD_Response *response)
{
  abort_refunds (ac);
  ac->response_code = response_code;
  ac->response = response;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Resuming /abort handling as exchange interaction is done (%u)\n",
              response_code);
  if (NULL != ac->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (ac->timeout_task);
    ac->timeout_task = NULL;
  }
  GNUNET_assert (GNUNET_YES == ac->suspended);
  ac->suspended = GNUNET_NO;
  MHD_resume_connection (ac->connection);
  TMH_trigger_daemon (); /* we resumed, kick MHD */
}


/**
 * Resume abortment processing with an error.
 *
 * @param ac operation to resume
 * @param http_status http status code to return
 * @param ec taler error code to return
 * @param msg human readable error message
 */
static void
resume_abort_with_error (struct AbortContext *ac,
                         unsigned int http_status,
                         enum TALER_ErrorCode ec,
                         const char *msg)
{
  resume_abort_with_response (ac,
                              http_status,
                              TALER_MHD_make_error (ec,
                                                    msg));
}


/**
 * Generate a response that indicates abortment success.
 *
 * @param ac abortment context
 */
static void
generate_success_response (struct AbortContext *ac)
{
  json_t *refunds;

  refunds = json_array ();
  if (NULL == refunds)
  {
    GNUNET_break (0);
    resume_abort_with_error (ac,
                             MHD_HTTP_INTERNAL_SERVER_ERROR,
                             TALER_EC_GENERIC_JSON_ALLOCATION_FAILURE,
                             "could not create JSON array");
    return;
  }
  for (unsigned int i = 0; i<ac->coins_cnt; i++)
  {
    struct RefundDetails *rdi = &ac->rd[i];
    json_t *detail;

    detail = (MHD_HTTP_OK != rdi->http_status)
             ? json_pack ("{s:s, s:I, s:I, s:O}",
                          "type",
                          "failure",
                          "exchange_status",
                          (json_int_t) rdi->http_status,
                          "exchange_code",
                          (json_int_t) TALER_JSON_get_error_code (
                            rdi->exchange_reply),
                          "exchange_reply",
                          rdi->exchange_reply)
             : json_pack ("{s:s, s:I, s:o, s:o}",
                          "type",
                          "success",
                          "exchange_status",
                          (json_int_t) rdi->http_status,
                          "exchange_sig",
                          GNUNET_JSON_from_data_auto (&rdi->exchange_sig),
                          "exchange_pub",
                          GNUNET_JSON_from_data_auto (&rdi->exchange_pub));
    if ( (NULL == detail) ||
         (0 != json_array_append_new (refunds,
                                      detail)) )
    {
      json_decref (refunds);
      GNUNET_break (0);
      resume_abort_with_error (ac,
                               MHD_HTTP_INTERNAL_SERVER_ERROR,
                               TALER_EC_GENERIC_JSON_ALLOCATION_FAILURE,
                               "could not create JSON array");
      return;
    }
  }

  /* Resume and send back the response.  */
  resume_abort_with_response (ac,
                              MHD_HTTP_OK,
                              TALER_MHD_make_json_pack ("{s:o}",
                                                        "refunds",
                                                        refunds));
}


/**
 * Custom cleanup routine for a `struct AbortContext`.
 *
 * @param cls the `struct AbortContext` to clean up.
 */
static void
abort_context_cleanup (void *cls)
{
  struct AbortContext *ac = cls;

  if (NULL != ac->timeout_task)
  {
    GNUNET_SCHEDULER_cancel (ac->timeout_task);
    ac->timeout_task = NULL;
  }
  abort_refunds (ac);
  for (unsigned int i = 0; i<ac->coins_cnt; i++)
  {
    struct RefundDetails *rdi = &ac->rd[i];

    if (NULL != rdi->exchange_reply)
    {
      json_decref (rdi->exchange_reply);
      rdi->exchange_reply = NULL;
    }
    GNUNET_free (rdi->exchange_url);
  }
  GNUNET_free (ac->rd);
  if (NULL != ac->fo)
  {
    TMH_EXCHANGES_find_exchange_cancel (ac->fo);
    ac->fo = NULL;
  }
  if (NULL != ac->response)
  {
    MHD_destroy_response (ac->response);
    ac->response = NULL;
  }
  GNUNET_CONTAINER_DLL_remove (ac_head,
                               ac_tail,
                               ac);
  GNUNET_free (ac);
}


/**
 * Find the exchange we need to talk to for the next
 * pending deposit permission.
 *
 * @param ac abortment context we are processing
 */
static void
find_next_exchange (struct AbortContext *ac);


/**
 * Function called with the result from the exchange (to be
 * passed back to the wallet).
 *
 * @param cls closure
 * @param hr HTTP response data
 * @param sign_key exchange key used to sign @a obj, or NULL
 * @param signature the actual signature, or NULL on error
 */
static void
refund_cb (void *cls,
           const struct TALER_EXCHANGE_HttpResponse *hr,
           const struct TALER_ExchangePublicKeyP *sign_key,
           const struct TALER_ExchangeSignatureP *signature)
{
  struct RefundDetails *rd = cls;
  struct AbortContext *ac = rd->ac;

  (void) sign_key;
  (void) signature;
  rd->rh = NULL;
  rd->http_status = hr->http_status;
  rd->exchange_reply = json_incref ((json_t*) hr->reply);
  if (MHD_HTTP_OK == hr->http_status)
  {
    GNUNET_assert (NULL != sign_key);
    GNUNET_assert (NULL != signature);
    rd->exchange_pub = *sign_key;
    rd->exchange_sig = *signature;
  }
  ac->pending_at_ce--;
  if (0 == ac->pending_at_ce)
    find_next_exchange (ac);
}


/**
 * Function called with the result of our exchange lookup.
 *
 * @param cls the `struct AbortContext`
 * @param hr HTTP response details
 * @param payto_uri payto://-URI of the exchange
 * @param exchange_handle NULL if exchange was not found to be acceptable
 * @param wire_fee current applicable fee for dealing with @a exchange_handle,
 *        NULL if not available
 * @param exchange_trusted true if this exchange is
 *        trusted by config
 */
static void
process_abort_with_exchange (void *cls,
                             const struct TALER_EXCHANGE_HttpResponse *hr,
                             struct TALER_EXCHANGE_Handle *exchange_handle,
                             const char *payto_uri,
                             const struct TALER_Amount *wire_fee,
                             bool exchange_trusted)
{
  struct AbortContext *ac = cls;

  (void) payto_uri;
  (void) exchange_trusted;
  ac->fo = NULL;
  GNUNET_assert (GNUNET_YES == ac->suspended);
  if (NULL == hr)
  {
    resume_abort_with_response (
      ac,
      MHD_HTTP_GATEWAY_TIMEOUT,
      TALER_MHD_make_json_pack (
        "{s:s, s:I}",
        "hint",
        TALER_ErrorCode_get_hint (
          TALER_EC_MERCHANT_GENERIC_EXCHANGE_TIMEOUT),
        "code",
        (json_int_t) TALER_EC_MERCHANT_GENERIC_EXCHANGE_TIMEOUT));
    return;
  }
  if (NULL == exchange_handle)
  {
    /* The request failed somehow */
    GNUNET_break_op (0);
    resume_abort_with_response (
      ac,
      MHD_HTTP_BAD_GATEWAY,
      TALER_MHD_make_json_pack (
        "{s:s, s:I, s:I, s:I, s:O?}",
        "hint", TALER_ErrorCode_get_hint (
          TALER_EC_MERCHANT_GENERIC_EXCHANGE_CONNECT_FAILURE),
        "code", (json_int_t) TALER_EC_MERCHANT_GENERIC_EXCHANGE_CONNECT_FAILURE,
        "exchange_http_status", (json_int_t) hr->http_status,
        "exchange_code", (json_int_t) hr->ec,
        "exchange_reply", hr->reply));
    return;
  }
  /* Initiate refund operation for all coins of
     the current exchange (!) */
  GNUNET_assert (0 == ac->pending_at_ce);
  for (unsigned int i = 0; i<ac->coins_cnt; i++)
  {
    struct RefundDetails *rdi = &ac->rd[i];

    if (rdi->processed)
      continue;
    GNUNET_assert (NULL == rdi->rh);
    if (0 != strcmp (rdi->exchange_url,
                     ac->current_exchange))
      continue;
    rdi->processed = true;
    ac->pending--;
    rdi->rh = TALER_EXCHANGE_refund (exchange_handle,
                                     &rdi->amount_with_fee,
                                     &ac->h_contract_terms,
                                     &rdi->coin_pub,
                                     0, /* rtransaction_id */
                                     &ac->hc->instance->merchant_priv,
                                     &refund_cb,
                                     rdi);
    if (NULL == rdi->rh)
    {
      GNUNET_break_op (0);
      resume_abort_with_error (ac,
                               MHD_HTTP_INTERNAL_SERVER_ERROR,
                               TALER_EC_MERCHANT_POST_ORDERS_ID_ABORT_EXCHANGE_REFUND_FAILED,
                               "Failed to start refund with exchange");
      return;
    }
    ac->pending_at_ce++;
  }
}


/**
 * Begin of the DB transaction.  If required (from
 * soft/serialization errors), the transaction can be
 * restarted here.
 *
 * @param ac abortment context to transact
 */
static void
begin_transaction (struct AbortContext *ac);


/**
 * Find the exchange we need to talk to for the next
 * pending deposit permission.
 *
 * @param ac abortment context we are processing
 */
static void
find_next_exchange (struct AbortContext *ac)
{
  for (unsigned int i = 0; i<ac->coins_cnt; i++)
  {
    struct RefundDetails *rdi = &ac->rd[i];

    if (! rdi->processed)
    {
      ac->current_exchange = rdi->exchange_url;
      ac->fo = TMH_EXCHANGES_find_exchange (ac->current_exchange,
                                            NULL,
                                            GNUNET_NO,
                                            &process_abort_with_exchange,
                                            ac);
      if (NULL == ac->fo)
      {
        GNUNET_break (0);
        resume_abort_with_error (ac,
                                 MHD_HTTP_INTERNAL_SERVER_ERROR,
                                 TALER_EC_MERCHANT_POST_ORDERS_ID_ABORT_EXCHANGE_LOOKUP_FAILED,
                                 "Failed to lookup exchange by URL");
        return;
      }
      return;
    }
  }
  ac->current_exchange = NULL;
  GNUNET_assert (0 == ac->pending);
  /* We are done with all the HTTP requests, go back and try
     the 'big' database transaction! (It should work now!) */
  begin_transaction (ac);
}


/**
 * Function called with information about a coin that was deposited.
 *
 * @param cls closure
 * @param exchange_url exchange where @a coin_pub was deposited
 * @param coin_pub public key of the coin
 * @param amount_with_fee amount the exchange will deposit for this coin
 * @param deposit_fee fee the exchange will charge for this coin
 * @param refund_fee fee the exchange will charge for refunding this coin
 * @param wire_fee wire fee the exchange of this coin charges
 */
static void
refund_coins (void *cls,
              const char *exchange_url,
              const struct TALER_CoinSpendPublicKeyP *coin_pub,
              const struct TALER_Amount *amount_with_fee,
              const struct TALER_Amount *deposit_fee,
              const struct TALER_Amount *refund_fee,
              const struct TALER_Amount *wire_fee)
{
  struct AbortContext *ac = cls;
  struct GNUNET_TIME_Absolute now;

  (void) amount_with_fee;
  (void) deposit_fee;
  (void) refund_fee;
  (void) wire_fee;
  now = GNUNET_TIME_absolute_get ();
  for (unsigned int i = 0; i<ac->coins_cnt; i++)
  {
    struct RefundDetails *rdi = &ac->rd[i];
    enum GNUNET_DB_QueryStatus qs;

    if ( (0 !=
          GNUNET_memcmp (coin_pub,
                         &rdi->coin_pub)) ||
         (0 !=
          strcmp (exchange_url,
                  rdi->exchange_url)) )
      continue; /* not in request */

    /* Store refund in DB */
    qs = TMH_db->refund_coin (TMH_db->cls,
                              ac->hc->instance->settings.id,
                              &ac->h_contract_terms,
                              now,
                              coin_pub,
                              /* justification */
                              "incomplete abortment aborted");
    if (0 > qs)
    {
      TMH_db->rollback (TMH_db->cls);
      if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
      {
        begin_transaction (ac);
        return;
      }
      /* Always report on hard error as well to enable diagnostics */
      GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
      resume_abort_with_error (ac,
                               MHD_HTTP_INTERNAL_SERVER_ERROR,
                               TALER_EC_GENERIC_DB_STORE_FAILED,
                               "refund_coin");
      return;
    }
  } /* for all coins */
}


/**
 * Begin of the DB transaction.  If required (from soft/serialization errors),
 * the transaction can be restarted here.
 *
 * @param ac abortment context to transact
 */
static void
begin_transaction (struct AbortContext *ac)
{
  enum GNUNET_DB_QueryStatus qs;

  /* Avoid re-trying transactions on soft errors forever! */
  if (ac->retry_counter++ > MAX_RETRIES)
  {
    GNUNET_break (0);
    resume_abort_with_error (ac,
                             MHD_HTTP_INTERNAL_SERVER_ERROR,
                             TALER_EC_GENERIC_DB_SOFT_FAILURE,
                             NULL);
    return;
  }
  GNUNET_assert (GNUNET_YES == ac->suspended);

  /* First, try to see if we have all we need already done */
  TMH_db->preflight (TMH_db->cls);
  if (GNUNET_OK !=
      TMH_db->start (TMH_db->cls,
                     "run abort"))
  {
    GNUNET_break (0);
    resume_abort_with_error (ac,
                             MHD_HTTP_INTERNAL_SERVER_ERROR,
                             TALER_EC_GENERIC_DB_START_FAILED,
                             NULL);
    return;
  }

  /* check payment was indeed incomplete
     (now that we are in the transaction scope!) */
  {
    struct GNUNET_HashCode h_contract_terms;
    bool paid;

    qs = TMH_db->lookup_order_status (TMH_db->cls,
                                      ac->hc->instance->settings.id,
                                      ac->hc->infix,
                                      &h_contract_terms,
                                      &paid);
    switch (qs)
    {
    case GNUNET_DB_STATUS_SOFT_ERROR:
    case GNUNET_DB_STATUS_HARD_ERROR:
      /* Always report on hard error to enable diagnostics */
      GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
      TMH_db->rollback (TMH_db->cls);
      if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
      {
        begin_transaction (ac);
        return;
      }
      /* Always report on hard error as well to enable diagnostics */
      GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
      resume_abort_with_error (ac,
                               MHD_HTTP_INTERNAL_SERVER_ERROR,
                               TALER_EC_GENERIC_DB_FETCH_FAILED,
                               "order status");
      return;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      TMH_db->rollback (TMH_db->cls);
      resume_abort_with_error (ac,
                               MHD_HTTP_NOT_FOUND,
                               TALER_EC_MERCHANT_POST_ORDERS_ID_ABORT_CONTRACT_NOT_FOUND,
                               "Could not find contract");
      return;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      if (paid)
      {
        /* Payment is complete, refuse to abort. */
        TMH_db->rollback (TMH_db->cls);
        resume_abort_with_error (ac,
                                 MHD_HTTP_PRECONDITION_FAILED,
                                 TALER_EC_MERCHANT_POST_ORDERS_ID_ABORT_REFUND_REFUSED_PAYMENT_COMPLETE,
                                 "Payment was complete, refusing to abort");
        return;
      }
    }
    if (0 !=
        GNUNET_memcmp (&ac->h_contract_terms,
                       &h_contract_terms))
    {
      GNUNET_break_op (0);
      resume_abort_with_error (ac,
                               MHD_HTTP_FORBIDDEN,
                               TALER_EC_MERCHANT_POST_ORDERS_ID_ABORT_CONTRACT_HASH_MISSMATCH,
                               "Provided hash does not match order on file");
      return;
    }
  }

  /* Mark all deposits we have in our database for the order as refunded. */
  qs = TMH_db->lookup_deposits (TMH_db->cls,
                                ac->hc->instance->settings.id,
                                &ac->h_contract_terms,
                                &refund_coins,
                                ac);
  if (0 > qs)
  {
    TMH_db->rollback (TMH_db->cls);
    if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
    {
      begin_transaction (ac);
      return;
    }
    /* Always report on hard error as well to enable diagnostics */
    GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
    resume_abort_with_error (ac,
                             MHD_HTTP_INTERNAL_SERVER_ERROR,
                             TALER_EC_GENERIC_DB_FETCH_FAILED,
                             "deposits");
    return;
  }

  qs = TMH_db->commit (TMH_db->cls);
  if (0 > qs)
  {
    TMH_db->rollback (TMH_db->cls);
    if (GNUNET_DB_STATUS_SOFT_ERROR == qs)
    {
      begin_transaction (ac);
      return;
    }
    resume_abort_with_error (ac,
                             MHD_HTTP_INTERNAL_SERVER_ERROR,
                             TALER_EC_GENERIC_DB_COMMIT_FAILED,
                             NULL);
    return;
  }

  /* At this point, the refund got correctly committed
     into the database. Tell exchange about abort/refund. */
  if (ac->pending > 0)
  {
    find_next_exchange (ac);
    return;
  }
  generate_success_response (ac);
}


/**
 * Try to parse the abort request into the given abort context.
 * Schedules an error response in the connection on failure.
 *
 * @param connection HTTP connection we are receiving abortment on
 * @param hc context we use to handle the abortment
 * @param ac state of the /abort call
 * @return #GNUNET_OK on success,
 *         #GNUNET_NO on failure (response was queued with MHD)
 *         #GNUNET_SYSERR on hard error (MHD connection must be dropped)
 */
static enum GNUNET_GenericReturnValue
parse_abort (struct MHD_Connection *connection,
             struct TMH_HandlerContext *hc,
             struct AbortContext *ac)
{
  json_t *coins;
  struct GNUNET_JSON_Specification spec[] = {
    GNUNET_JSON_spec_json ("coins",
                           &coins),
    GNUNET_JSON_spec_fixed_auto ("h_contract",
                                 &ac->h_contract_terms),

    GNUNET_JSON_spec_end ()
  };
  enum GNUNET_GenericReturnValue res;

  res = TALER_MHD_parse_json_data (connection,
                                   hc->request_body,
                                   spec);
  if (GNUNET_YES != res)
  {
    GNUNET_break_op (0);
    return res;
  }
  ac->coins_cnt = json_array_size (coins);
  if (0 == ac->coins_cnt)
  {
    GNUNET_JSON_parse_free (spec);
    return TALER_MHD_reply_with_error (connection,
                                       MHD_HTTP_BAD_REQUEST,
                                       TALER_EC_MERCHANT_POST_ORDERS_ID_ABORT_COINS_ARRAY_EMPTY,
                                       "coins");
  }
  /* note: 1 coin = 1 deposit confirmation expected */
  ac->pending = ac->coins_cnt;
  ac->rd = GNUNET_new_array (ac->coins_cnt,
                             struct RefundDetails);
  /* This loop populates the array 'rd' in 'ac' */
  {
    unsigned int coins_index;
    json_t *coin;
    json_array_foreach (coins, coins_index, coin)
    {
      struct RefundDetails *rd = &ac->rd[coins_index];
      const char *exchange_url;
      struct GNUNET_JSON_Specification ispec[] = {
        TALER_JSON_spec_amount ("contribution",
                                &rd->amount_with_fee),
        GNUNET_JSON_spec_string ("exchange_url",
                                 &exchange_url),
        GNUNET_JSON_spec_fixed_auto ("coin_pub",
                                     &rd->coin_pub),
        GNUNET_JSON_spec_end ()
      };

      res = TALER_MHD_parse_json_data (connection,
                                       coin,
                                       ispec);
      if (GNUNET_YES != res)
      {
        GNUNET_JSON_parse_free (spec);
        GNUNET_break_op (0);
        return res;
      }
      rd->exchange_url = GNUNET_strdup (exchange_url);
      rd->index = coins_index;
      rd->ac = ac;
    }
  }
  GNUNET_JSON_parse_free (spec);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Handling /abort for order `%s' with contract hash `%s'\n",
              ac->hc->infix,
              GNUNET_h2s (&ac->h_contract_terms));
  return GNUNET_OK;
}


/**
 * Handle a timeout for the processing of the abort request.
 *
 * @param cls our `struct AbortContext`
 */
static void
handle_abort_timeout (void *cls)
{
  struct AbortContext *ac = cls;

  ac->timeout_task = NULL;
  GNUNET_assert (GNUNET_YES == ac->suspended);
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Resuming abort with error after timeout\n");
  if (NULL != ac->fo)
  {
    TMH_EXCHANGES_find_exchange_cancel (ac->fo);
    ac->fo = NULL;
  }
  resume_abort_with_error (ac,
                           MHD_HTTP_GATEWAY_TIMEOUT,
                           TALER_EC_MERCHANT_GENERIC_EXCHANGE_TIMEOUT,
                           NULL);
}


MHD_RESULT
TMH_post_orders_ID_abort (const struct TMH_RequestHandler *rh,
                          struct MHD_Connection *connection,
                          struct TMH_HandlerContext *hc)
{
  struct AbortContext *ac = hc->ctx;

  if (NULL == ac)
  {
    ac = GNUNET_new (struct AbortContext);
    GNUNET_CONTAINER_DLL_insert (ac_head,
                                 ac_tail,
                                 ac);
    ac->connection = connection;
    ac->hc = hc;
    hc->ctx = ac;
    hc->cc = &abort_context_cleanup;
  }
  if (GNUNET_SYSERR == ac->suspended)
    return MHD_NO; /* during shutdown, we don't generate any more replies */
  if (0 != ac->response_code)
  {
    MHD_RESULT res;

    /* We are *done* processing the request,
       just queue the response (!) */
    if (UINT_MAX == ac->response_code)
    {
      GNUNET_break (0);
      return MHD_NO; /* hard error */
    }
    res = MHD_queue_response (connection,
                              ac->response_code,
                              ac->response);
    MHD_destroy_response (ac->response);
    ac->response = NULL;
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Queueing response (%u) for /abort (%s).\n",
                (unsigned int) ac->response_code,
                res ? "OK" : "FAILED");
    return res;
  }
  {
    enum GNUNET_GenericReturnValue ret;

    ret = parse_abort (connection,
                       hc,
                       ac);
    if (GNUNET_OK != ret)
      return (GNUNET_NO == ret)
             ? MHD_YES
             : MHD_NO;
  }

  /* Abort not finished, suspend while we interact with the exchange */
  GNUNET_assert (GNUNET_NO == ac->suspended);
  MHD_suspend_connection (connection);
  ac->suspended = GNUNET_YES;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Suspending abort handling while working with the exchange\n");
  ac->timeout_task = GNUNET_SCHEDULER_add_delayed (ABORT_GENERIC_TIMEOUT,
                                                   &handle_abort_timeout,
                                                   ac);
  begin_transaction (ac);
  return MHD_YES;
}


/* end of taler-merchant-httpd_post-orders-ID-abort.c */