summaryrefslogtreecommitdiff
path: root/src/backend/taler-merchant-httpd_get-orders-ID.c
blob: 8d75bbf2010a5bf127efe93eae67fece1c6d5b4f (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
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
/*
  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 backend/taler-merchant-httpd_get-orders-ID.c
 * @brief implementation of GET /orders/$ID
 * @author Marcello Stanisci
 * @author Christian Grothoff
 */
#include "platform.h"
#include <jansson.h>
#include <qrencode.h>
#include <taler/taler_signatures.h>
#include <taler/taler_json_lib.h>
#include <taler/taler_exchange_service.h>
#include "taler-merchant-httpd_exchanges.h"
#include "taler-merchant-httpd_get-orders-ID.h"
#include "../mustach/mustach.h"

/**
 * How often do we retry DB transactions on serialization failures?
 */
#define MAX_RETRIES 5

/**
 * Information we keep for each coin to be refunded.
 */
struct CoinRefund
{

  /**
   * Kept in a DLL.
   */
  struct CoinRefund *next;

  /**
   * Kept in a DLL.
   */
  struct CoinRefund *prev;

  /**
   * Request to connect to the target exchange.
   */
  struct TMH_EXCHANGES_FindOperation *fo;

  /**
   * Handle for the refund operation with the exchange.
   */
  struct TALER_EXCHANGE_RefundHandle *rh;

  /**
   * Request this operation is part of.
   */
  struct GetOrderData *god;

  /**
   * URL of the exchange for this @e coin_pub.
   */
  char *exchange_url;

  /**
   * Fully reply from the exchange, only possibly set if
   * we got a JSON reply and a non-#MHD_HTTP_OK error code
   */
  json_t *exchange_reply;

  /**
   * When did the merchant grant the refund. To be used to group events
   * in the wallet.
   */
  struct GNUNET_TIME_Absolute execution_time;

  /**
   * Coin to refund.
   */
  struct TALER_CoinSpendPublicKeyP coin_pub;

  /**
   * Refund transaction ID to use.
   */
  uint64_t rtransaction_id;

  /**
   * Unique serial number identifying the refund.
   */
  uint64_t refund_serial;

  /**
   * Amount to refund.
   */
  struct TALER_Amount refund_amount;

  /**
   * Public key of the exchange affirming the refund.
   */
  struct TALER_ExchangePublicKeyP exchange_pub;

  /**
   * Signature of the exchange affirming the refund.
   */
  struct TALER_ExchangeSignatureP exchange_sig;

  /**
   * HTTP status from the exchange, #MHD_HTTP_OK if
   * @a exchange_pub and @a exchange_sig are valid.
   */
  unsigned int exchange_status;

  /**
   * HTTP error code from the exchange.
   */
  enum TALER_ErrorCode exchange_code;

};


/**
 * Context for the operation.
 */
struct GetOrderData
{

  /**
   * Hashed version of contract terms. All zeros if
   * not provided.
   */
  struct GNUNET_HashCode h_contract_terms;

  /**
   * Claim token used for access control. All zeros if
   * not provided.
   */
  struct TALER_ClaimTokenP claim_token;

  /**
   * DLL of (suspended) requests.
   */
  struct GetOrderData *next;

  /**
   * DLL of (suspended) requests.
   */
  struct GetOrderData *prev;

  /**
   * Refunds for this order. Head of DLL.
   */
  struct CoinRefund *cr_head;

  /**
   * Refunds for this order. Tail of DLL.
   */
  struct CoinRefund *cr_tail;

  /**
   * Context of the request.
   */
  struct TMH_HandlerContext *hc;

  /**
   * Entry in the #resume_timeout_heap for this check payment, if we are
   * suspended.
   */
  struct TMH_SuspendedConnection sc;

  /**
   * Which merchant instance is this for?
   */
  struct MerchantInstance *mi;

  /**
   * order ID for the payment
   */
  const char *order_id;

  /**
   * Where to get the contract
   */
  const char *contract_url;

  /**
   * fulfillment URL of the contract (valid as long as
   * @e contract_terms is valid).
   */
  const char *fulfillment_url;

  /**
   * session of the client
   */
  const char *session_id;

  /**
   * Contract terms of the payment we are checking. NULL when they
   * are not (yet) known.
   */
  json_t *contract_terms;

  /**
   * Total refunds granted for this payment. Only initialized
   * if @e refunded is set to true.
   */
  struct TALER_Amount refund_amount;

  /**
   * Did we suspend @a connection?
   */
  bool suspended;

  /**
   * Return code: #TALER_EC_NONE if successful.
   */
  enum TALER_ErrorCode ec;

  /**
   * Set to true if we are dealing with an unclaimed order
   * (and thus @e h_contract_terms is not set, and certain
   * DB queries will not work).
   */
  bool unclaimed;

  /**
   * Set to true if this payment has been refunded and
   * @e refund_amount is initialized.
   */
  bool refunded;

  /**
   * Set to true if the client requested HTML, otherwise
   * we generate JSON.
   */
  bool generate_html;

};


/**
 * Entry in a key-value array we use as the mustach closure.
 */
struct KVC
{
  /**
   * A name, used as the key. NULL for the last entry.
   */
  const char *name;

  /**
   * 0-terminated string value to return for @e name.
   */
  char *value;
};


/**
 * Entry in a key-value array we use to cache templates.
 */
struct TVE
{
  /**
   * A name, used as the key. NULL for the last entry.
   */
  const char *name;

  /**
   * 0-terminated (!) file data to return for @e name.
   */
  char *value;

};


/**
 * Head of DLL of (suspended) requests.
 */
static struct GetOrderData *god_head;

/**
 * Tail of DLL of (suspended) requests.
 */
static struct GetOrderData *god_tail;

/**
 * Templated loaded into RAM.
 */
static struct TVE *loaded;

/**
 * Length of the #loaded array.
 */
static unsigned int loaded_length;


/**
 * Function called by Mustach to enter the section @a name.
 * As we do not support sections, we always return 0.
 *
 * @param cls a `struct KVC[]` array
 * @param name section to enter
 * @return 0 (do not enter)
 */
static int
m_enter (void *cls, const char *name)
{
  (void) cls;
  (void) name;
  return 0;
}


/**
 * Function called by mustach to activate the next item in the
 * section. Does nothing, as we do not support sections.
 *
 * @param cls a `struct KVC[]` array
 * @return 0 (no next item to activate)
 */
static int
m_next (void *cls)
{
  (void) cls;
  return 0;
}


/**
 * Function called by Mustach to leave the current section.
 * As we do not support sections, we should never be called.
 *
 * @param cls a `struct KVC[]` array
 * @return 0 (not documented by mustach)
 */
static int
m_leave (void *cls)
{
  GNUNET_assert (0);
  return 0;
}


/**
 * Return the value of @a name in @a sbuf.
 *
 * @param cls a `struct KVC[]` array
 * @param name the value to lookup
 * @param[out] sbuf where to return the data
 * @return mustach-defined status code
 */
static int
m_get (void *cls,
       const char *name,
       struct mustach_sbuf *sbuf)
{
  struct KVC *kvc = cls;

  for (unsigned int i = 0; NULL != kvc[i].name; i++)
  {
    if (0 == strcmp (name,
                     kvc[i].name))
    {
      sbuf->value = kvc[i].value;
      sbuf->releasecb = NULL;
      sbuf->closure = &kvc[i];
      return MUSTACH_OK;
    }
  }
  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
              "Template requires value for unexpected name `%s'\n",
              name);
  return MUSTACH_ERROR_ITEM_NOT_FOUND;
}


/**
 * Mustach callback at the end. Cleans up the @a cls.
 *
 * @param cls a `struct KVC[]` array
 * @param status status of mustach (ignored)
 */
static void
m_stop (void *cls,
        int status)
{
  struct KVC *kvc = cls;

  (void) status;
  for (unsigned int i = 0; NULL != kvc[i].name; i++)
    GNUNET_free (kvc[i].value);
}


/**
 * Our 'universal' callbacks for mustach.
 */
static struct mustach_itf itf = {
  .enter = &m_enter,
  .next = &m_next,
  .leave = &m_leave,
  .get = &m_get,
  .stop = &m_stop
};


/**
 * Load Mustach template into memory.  Note that we intentionally cache
 * failures, that is if we ever failed to load a template, we will never try
 * again.
 *
 * FIXME: support i18n: evaluate Language: header from the browser!
 *
 * @param name name of the template file to load
 *        (MUST be a 'static' string in memory!)
 * @return NULL on error, otherwise the template
 */
static const char *
load_template (const char *name)
{
  char *fn;
  char *map;
  int fd;
  struct stat sb;

  for (unsigned int i = 0; i<loaded_length; i++)
  {
    if (0 == strcmp (loaded[i].name,
                     name))
      return loaded[i].value;
  }
  GNUNET_array_grow (loaded,
                     loaded_length,
                     loaded_length + 1);
  loaded[loaded_length - 1].name = name;
  {
    char *path;

    path = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR);
    if (NULL == path)
    {
      GNUNET_break (0);
      return NULL;
    }
    GNUNET_asprintf (&fn,
                     "%s/merchant/%s.must",
                     path,
                     name);
    GNUNET_free (path);
  }
  fd = open (fn, O_RDONLY);
  if (-1 == fd)
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                              "open",
                              fn);
    GNUNET_free (fn);
    return NULL;
  }
  if (0 !=
      fstat (fd,
             &sb))
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                              "open",
                              fn);
    GNUNET_free (fn);
    GNUNET_break (0 == close (fd));
    return NULL;
  }
  map = GNUNET_malloc_large (sb.st_size + 1);
  if (NULL == map)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                         "malloc");
    GNUNET_free (fn);
    GNUNET_break (0 == close (fd));
    return NULL;
  }
  if (sb.st_size !=
      read (fd,
            map,
            sb.st_size))
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                              "read",
                              fn);
    GNUNET_free (fn);
    GNUNET_break (0 == close (fd));
    return NULL;
  }
  GNUNET_break (0 == close (fd));
  GNUNET_free (fn);
  loaded[loaded_length - 1].value = map;
  return loaded[loaded_length - 1].value;
}


/**
 * Create the QR code image for a URI.
 *
 * @param uri input string to encode
 * @return NULL on error, encoded URI otherwise
 */
static char *
create_qrcode (const char *uri)
{
  QRinput *qri;
  QRcode *qrc;
  struct GNUNET_Buffer buf = { 0 };

  qri = QRinput_new2 (0,
                      QR_ECLEVEL_M);
  if (NULL == qri)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "QRinput_new2");
    return NULL;
  }
  /* first try encoding as uppercase-only alpha-numerical
     QR code (much smaller encoding); if that fails, also
     try using binary encoding */
  if ( (0 !=
        QRinput_append (qri,
                        QR_MODE_AN,
                        strlen (uri),
                        (unsigned char *) uri)) &&
       (0 !=
        QRinput_append (qri,
                        QR_MODE_8,
                        strlen (uri),
                        (unsigned char *) uri)) )
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "QRinput_append");
    QRinput_free (qri);
    return NULL;
  }
  qrc = QRcode_encodeInput (qri);
  if (NULL == qrc)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "QRcode_encodeInput");
    QRinput_free (qri);
    return NULL;
  }
  QRinput_free (qri);
  /* FIXME-Dold: generate <img> with inline SVG instead of <pre> here! */
  GNUNET_buffer_write_str (&buf,
                           "<p class=\"qrtext\"><br>\n<br>\n<br>\n<br>\n");
  for (unsigned int y = 0; y<qrc->width; y++)
  {
    GNUNET_buffer_write_str (&buf,
                             "&nbsp;&nbsp;&nbsp;&nbsp;");
    for (unsigned int x = 0; x<qrc->width; x++)
    {
      unsigned int off = x + y * qrc->width;
      GNUNET_buffer_write_fstr (&buf,
                                "%s",
                                (0 != (qrc->data[off] & 1))
                                ? "██"
                                : "&nbsp;&nbsp;");
    }
    GNUNET_buffer_write_str (&buf,
                             "&nbsp;&nbsp;&nbsp;&nbsp;<br>");
  }
  GNUNET_buffer_write_str (&buf,
                           "<br>\n<br>\n<br>\n<br>\n</p>");
  QRcode_free (qrc);
  return GNUNET_buffer_reap_str (&buf);
}


/**
 * Force resuming all suspended order lookups, needed during shutdown.
 */
void
TMH_force_wallet_get_order_resume (void)
{
  struct GetOrderData *god;

  while (NULL != (god = god_head))
  {
    GNUNET_CONTAINER_DLL_remove (god_head,
                                 god_tail,
                                 god);
    GNUNET_assert (god->suspended);
    god->suspended = false;
    MHD_resume_connection (god->sc.con);
  }
}


/**
 * Suspend this @a god until the trigger is satisfied.
 *
 * @param god request to suspend
 */
static void
suspend_god (struct GetOrderData *god)
{
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Suspending GET /orders/%s\n",
              god->order_id);
  TMH_long_poll_suspend (god->order_id,
                         god->hc->instance,
                         &god->sc,
                         (god->sc.awaiting_refund)
                         ? &god->sc.refund_expected
                         : NULL);
}


/**
 * Create a taler://pay/ URI for the given @a con and @a order_id
 * and @a session_id and @a instance_id.
 *
 * @param con HTTP connection
 * @param order_id the order id
 * @param session_id session, may be NULL
 * @param instance_id instance, may be "default"
 * @param claim_token claim token for the order, may be NULL
 * @return corresponding taler://pay/ URI, or NULL on missing "host"
 */
char *
TMH_make_taler_pay_uri (struct MHD_Connection *con,
                        const char *order_id,
                        const char *session_id,
                        const char *instance_id,
                        struct TALER_ClaimTokenP *claim_token)
{
  const char *host;
  const char *forwarded_host;
  const char *uri_path;
  struct GNUNET_Buffer buf = { 0 };


  host = MHD_lookup_connection_value (con,
                                      MHD_HEADER_KIND,
                                      "Host");
  forwarded_host = MHD_lookup_connection_value (con,
                                                MHD_HEADER_KIND,
                                                "X-Forwarded-Host");

  uri_path = MHD_lookup_connection_value (con,
                                          MHD_HEADER_KIND,
                                          "X-Forwarded-Prefix");
  if (NULL != forwarded_host)
    host = forwarded_host;

  if (NULL == host)
  {
    GNUNET_break (0);
    return NULL;
  }

  GNUNET_assert (NULL != instance_id);
  GNUNET_assert (NULL != order_id);

  GNUNET_buffer_write_str (&buf,
                           "taler");
  if (GNUNET_NO == TALER_mhd_is_https (con))
    GNUNET_buffer_write_str (&buf,
                             "+http");
  GNUNET_buffer_write_str (&buf,
                           "://pay/");
  GNUNET_buffer_write_str (&buf,
                           host);
  if (NULL != uri_path)
    GNUNET_buffer_write_path (&buf,
                              uri_path);
  if (0 != strcmp ("default",
                   instance_id))
  {
    GNUNET_buffer_write_path (&buf,
                              "instances");
    GNUNET_buffer_write_path (&buf,
                              instance_id);
  }
  GNUNET_buffer_write_path (&buf,
                            order_id);
  GNUNET_buffer_write_path (&buf,
                            (session_id == NULL) ? "" : session_id);
  if ((NULL != claim_token) &&
      (GNUNET_NO == GNUNET_is_zero (claim_token)))
  {
    GNUNET_buffer_write_str (&buf,
                             "&c=");
    GNUNET_buffer_write_data_encoded (&buf,
                                      (char *) claim_token,
                                      sizeof (struct TALER_ClaimTokenP));
  }

  return GNUNET_buffer_reap_str (&buf);
}


/**
 * The client did not yet pay, send it the payment request.
 *
 * @param god check pay request context
 * @param already_paid_order_id if for the fulfillment URI there is
 *          already a paid order, this is the order ID to redirect
 *          the wallet to; NULL if not applicable
 * @return #MHD_YES on success
 */
static MHD_RESULT
send_pay_request (struct GetOrderData *god,
                  const char *already_paid_order_id)
{
  MHD_RESULT ret;
  char *taler_pay_uri;
  struct GNUNET_TIME_Relative remaining;

  remaining = GNUNET_TIME_absolute_get_remaining (god->sc.long_poll_timeout);
  if (0 != remaining.rel_value_us)
  {
    /* long polling: do not queue a response, suspend connection instead */
    suspend_god (god);
    return MHD_YES;
  }

  /* Check if resource_id has been paid for in the same session
   * with another order_id.
   */
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Sending payment request in /poll-payment\n");
  taler_pay_uri = TMH_make_taler_pay_uri (god->sc.con,
                                          god->order_id,
                                          god->session_id,
                                          god->hc->instance->settings.id,
                                          &god->claim_token);
  if (god->generate_html)
  {
    struct MHD_Response *reply;
    char *qr;
    char *body;
    size_t body_size;

    qr = create_qrcode (taler_pay_uri);
    if (NULL == qr)
    {
      GNUNET_break (0);
      return MHD_NO;
    }
    {
      struct KVC kvc[] = {
        { "taler_pay_uri",
          GNUNET_strdup (taler_pay_uri) },
        { "taler_pay_qrcode_svg",
          qr },
        { "order_summary",
          GNUNET_strdup ("FIXME") },
        { NULL, NULL }
      };
      const char *tmpl;
      int eno;

      tmpl = load_template ("request_payment");
      if (NULL == tmpl)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    "Failed to load template `%s'\n",
                    "request_payment");
        return MHD_NO; // FIXME: add nicer error reply...
      }
      if (0 !=
          (eno = mustach (tmpl,
                          &itf,
                          &kvc,
                          &body,
                          &body_size)))
      {
        GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                    "mustach failed with error %d\n",
                    eno);
        return MHD_NO;   // FIXME: add nicer error reply...
      }
    }

    reply = MHD_create_response_from_buffer (body_size,
                                             body,
                                             MHD_RESPMEM_MUST_FREE);
    if (NULL == reply)
    {
      GNUNET_break (0);
      return MHD_NO;
    }
    GNUNET_break (MHD_NO !=
                  MHD_add_response_header (reply,
                                           "Taler",
                                           taler_pay_uri));
    GNUNET_break (MHD_NO !=
                  MHD_add_response_header (reply,
                                           MHD_HTTP_HEADER_CONTENT_TYPE,
                                           "text/html"));
    ret = MHD_queue_response (god->sc.con,
                              MHD_HTTP_PAYMENT_REQUIRED,
                              reply);
    MHD_destroy_response (reply);
  }
  else
  {
    ret = TALER_MHD_reply_json_pack (god->sc.con,
                                     MHD_HTTP_PAYMENT_REQUIRED,
                                     "{s:s, s:s?}",
                                     "taler_pay_uri",
                                     taler_pay_uri,
                                     "already_paid_order_id",
                                     already_paid_order_id);
  }
  GNUNET_free (taler_pay_uri);
  return ret;
}


/**
 * Check if @a god has sub-activities still pending.
 *
 * @param god request to check
 * @return true if activities are still pending
 */
static bool
god_pending (struct GetOrderData *god)
{
  for (struct CoinRefund *cr = god->cr_head;
       NULL != cr;
       cr = cr->next)
  {
    if ( (NULL != cr->fo) ||
         (NULL != cr->rh) )
      return true;
  }
  return false;
}


/**
 * Check if @a god is ready to be resumed, and if so, do it.
 *
 * @param god refund request to be possibly ready
 */
static void
check_resume_god (struct GetOrderData *god)
{
  if (god_pending (god))
    return;
  GNUNET_CONTAINER_DLL_remove (god_head,
                               god_tail,
                               god);
  GNUNET_assert (god->suspended);
  god->suspended = false;
  MHD_resume_connection (god->sc.con);
  TMH_trigger_daemon ();
}


/**
 * Callbacks of this type are used to serve the result of submitting a
 * refund request to an exchange.
 *
 * @param cls a `struct CoinRefund`
 * @param hr HTTP response data
 * @param exchange_pub exchange key used to sign refund confirmation
 * @param exchange_sig exchange's signature over refund
 */
static void
refund_cb (void *cls,
           const struct TALER_EXCHANGE_HttpResponse *hr,
           const struct TALER_ExchangePublicKeyP *exchange_pub,
           const struct TALER_ExchangeSignatureP *exchange_sig)
{
  struct CoinRefund *cr = cls;

  cr->rh = NULL;
  cr->exchange_status = hr->http_status;
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Exchange refund status for coin %s is %u\n",
              TALER_B2S (&cr->coin_pub),
              hr->http_status);
  if (MHD_HTTP_OK != hr->http_status)
  {
    cr->exchange_code = hr->ec;
    cr->exchange_reply = json_incref ((json_t*) hr->reply);
  }
  else
  {
    enum GNUNET_DB_QueryStatus qs;

    cr->exchange_pub = *exchange_pub;
    cr->exchange_sig = *exchange_sig;
    qs = TMH_db->insert_refund_proof (TMH_db->cls,
                                      cr->refund_serial,
                                      exchange_sig,
                                      exchange_pub);
    if (0 >= qs)
    {
      /* generally, this is relatively harmless for the merchant, but let's at
         least log this. */
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Failed to persist exchange response to /refund in database: %d\n",
                  qs);
    }
  }
  check_resume_god (cr->god);
}


/**
 * Function called with the result of a #TMH_EXCHANGES_find_exchange()
 * operation.
 *
 * @param cls a `struct CoinRefund *`
 * @param hr HTTP response details
 * @param eh handle to the exchange context
 * @param payto_uri payto://-URI of the exchange
 * @param wire_fee current applicable wire fee for dealing with @a eh, NULL if not available
 * @param exchange_trusted true if this exchange is trusted by config
 */
static void
exchange_found_cb (void *cls,
                   const struct TALER_EXCHANGE_HttpResponse *hr,
                   struct TALER_EXCHANGE_Handle *eh,
                   const char *payto_uri,
                   const struct TALER_Amount *wire_fee,
                   bool exchange_trusted)
{
  struct CoinRefund *cr = cls;

  (void) payto_uri;
  cr->fo = NULL;
  if (TALER_EC_NONE == hr->ec)
  {
    cr->rh = TALER_EXCHANGE_refund (eh,
                                    &cr->refund_amount,
                                    &cr->god->h_contract_terms,
                                    &cr->coin_pub,
                                    cr->rtransaction_id,
                                    &cr->god->hc->instance->merchant_priv,
                                    &refund_cb,
                                    cr);
    return;
  }
  cr->exchange_status = hr->http_status;
  cr->exchange_code = hr->ec;
  cr->exchange_reply = json_incref ((json_t*) hr->reply);
  check_resume_god (cr->god);
}


/**
 * Function called with detailed information about a refund.
 * It is responsible for packing up the data to return.
 *
 * @param cls closure
 * @param refund_serial unique serial number of the refund
 * @param timestamp time of the refund (for grouping of refunds in the wallet UI)
 * @param coin_pub public coin from which the refund comes from
 * @param exchange_url URL of the exchange that issued @a coin_pub
 * @param rtransaction_id identificator of the refund
 * @param reason human-readable explanation of the refund
 * @param refund_amount refund amount which is being taken from @a coin_pub
 */
static void
process_refunds_cb (void *cls,
                    uint64_t refund_serial,
                    struct GNUNET_TIME_Absolute timestamp,
                    const struct TALER_CoinSpendPublicKeyP *coin_pub,
                    const char *exchange_url,
                    uint64_t rtransaction_id,
                    const char *reason,
                    const struct TALER_Amount *refund_amount)
{
  struct GetOrderData *god = cls;
  struct CoinRefund *cr;

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Found refund of %s for coin %s with reason `%s' in database\n",
              TALER_B2S (coin_pub),
              TALER_amount2s (refund_amount),
              reason);
  cr = GNUNET_new (struct CoinRefund);
  cr->refund_serial = refund_serial;
  cr->exchange_url = GNUNET_strdup (exchange_url);
  cr->god = god;
  cr->coin_pub = *coin_pub;
  cr->rtransaction_id = rtransaction_id;
  cr->refund_amount = *refund_amount;
  cr->execution_time = timestamp;
  GNUNET_CONTAINER_DLL_insert (god->cr_head,
                               god->cr_tail,
                               cr);
  if (god->refunded)
  {
    GNUNET_assert (0 <=
                   TALER_amount_add (&god->refund_amount,
                                     &god->refund_amount,
                                     refund_amount));
    return;
  }
  god->refund_amount = *refund_amount;
  god->refunded = true;
}


/**
 * Clean up refund processing.
 *
 * @param god handle to clean up refund processing for
 */
static void
rf_cleanup (struct GetOrderData *god)
{
  struct CoinRefund *cr;

  while (NULL != (cr = god->cr_head))
  {
    GNUNET_CONTAINER_DLL_remove (god->cr_head,
                                 god->cr_tail,
                                 cr);
    if (NULL != cr->fo)
    {
      TMH_EXCHANGES_find_exchange_cancel (cr->fo);
      cr->fo = NULL;
    }
    if (NULL != cr->rh)
    {
      TALER_EXCHANGE_refund_cancel (cr->rh);
      cr->rh = NULL;
    }
    if (NULL != cr->exchange_reply)
    {
      json_decref (cr->exchange_reply);
      cr->exchange_reply = NULL;
    }
    GNUNET_free (cr->exchange_url);
    GNUNET_free (cr);
  }
}


/**
 * Clean up the session state for a GET /orders/$ID request.
 *
 * @param cls must be a `struct GetOrderData *`
 */
static void
god_cleanup (void *cls)
{
  struct GetOrderData *god = cls;

  rf_cleanup (god);
  if (NULL != god->contract_terms)
    json_decref (god->contract_terms);
  GNUNET_free (god);
}


/**
 * Handle a GET "/orders/$ID" request.
 *
 * @param rh context of the handler
 * @param connection the MHD connection to handle
 * @param[in,out] hc context with further information about the request
 * @return MHD result code
 */
MHD_RESULT
TMH_get_orders_ID (const struct TMH_RequestHandler *rh,
                   struct MHD_Connection *connection,
                   struct TMH_HandlerContext *hc)
{
  struct GetOrderData *god = hc->ctx;
  const char *order_id = hc->infix;
  enum GNUNET_DB_QueryStatus qs;

  if (NULL == god)
  {
    god = GNUNET_new (struct GetOrderData);
    hc->ctx = god;
    hc->cc = &god_cleanup;
    god->sc.con = connection;
    god->hc = hc;
    god->order_id = order_id;

    {
      const char *ct;

      ct = MHD_lookup_connection_value (connection,
                                        MHD_GET_ARGUMENT_KIND,
                                        "token");
      if ( (NULL != ct) &&
           (GNUNET_OK !=
            GNUNET_STRINGS_string_to_data (ct,
                                           strlen (ct),
                                           &god->claim_token,
                                           sizeof (god->claim_token))) )
      {
        /* ct has wrong encoding */
        GNUNET_break_op (0);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_BAD_REQUEST,
                                           TALER_EC_PARAMETER_MALFORMED,
                                           "token malformed");
      }
    }

    {
      const char *cts;

      cts = MHD_lookup_connection_value (connection,
                                         MHD_GET_ARGUMENT_KIND,
                                         "h_contract");
      if ( (NULL != cts) &&
           (GNUNET_OK !=
            GNUNET_CRYPTO_hash_from_string (cts,
                                            &god->h_contract_terms)) )
      {
        /* cts has wrong encoding */
        GNUNET_break_op (0);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_BAD_REQUEST,
                                           TALER_EC_PARAMETER_MALFORMED,
                                           "h_contract malformed");
      }
    }

    { /* check for 'Accept' header */
      const char *accept;

      accept = MHD_lookup_connection_value (connection,
                                            MHD_HEADER_KIND,
                                            MHD_HTTP_HEADER_ACCEPT);
      if (NULL != accept)
      {
        char *a = GNUNET_strdup (accept);
        char *saveptr;

        for (char *t = strtok_r (a, ",", &saveptr);
             NULL != t;
             t = strtok_r (NULL, ",", &saveptr))
        {
          char *end;

          /* skip leading whitespace */
          while (isspace ((unsigned char) t[0]))
            t++;
          /* trim of ';q=' parameter and everything after space */
          end = strchr (t, ';');
          if (NULL != end)
            *end = '\0';
          end = strchr (t, ' ');
          if (NULL != end)
            *end = '\0';
          if (0 == strcasecmp ("text/html",
                               t))
          {
            god->generate_html = true;
            break;
          }
        }
        GNUNET_free (a);
      }
    } /* end check for 'Accept' header */

    {
      const char *long_poll_timeout_s;

      long_poll_timeout_s = MHD_lookup_connection_value (connection,
                                                         MHD_GET_ARGUMENT_KIND,
                                                         "timeout");
      if (NULL != long_poll_timeout_s)
      {
        unsigned int timeout;

        if (1 != sscanf (long_poll_timeout_s,
                         "%u",
                         &timeout))
        {
          GNUNET_break_op (0);
          return TALER_MHD_reply_with_error (connection,
                                             MHD_HTTP_BAD_REQUEST,
                                             TALER_EC_PARAMETER_MALFORMED,
                                             "timeout must be non-negative number");
        }
        god->sc.long_poll_timeout
          = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply (
                                                GNUNET_TIME_UNIT_SECONDS,
                                                timeout));
      }
      else
      {
        god->sc.long_poll_timeout = GNUNET_TIME_UNIT_ZERO_ABS;
      }
    }

    {
      const char *min_refund;

      min_refund = MHD_lookup_connection_value (connection,
                                                MHD_GET_ARGUMENT_KIND,
                                                "refund");
      if (NULL != min_refund)
      {
        if ( (GNUNET_OK !=
              TALER_string_to_amount (min_refund,
                                      &god->sc.refund_expected)) ||
             (0 != strcasecmp (god->sc.refund_expected.currency,
                               TMH_currency) ) )
        {
          GNUNET_break_op (0);
          return TALER_MHD_reply_with_error (connection,
                                             MHD_HTTP_BAD_REQUEST,
                                             TALER_EC_PARAMETER_MALFORMED,
                                             "invalid amount given for refund argument");
        }
        god->sc.awaiting_refund = true;
      }
    }

    god->session_id = MHD_lookup_connection_value (connection,
                                                   MHD_GET_ARGUMENT_KIND,
                                                   "session_id");

    /* Convert order_id to h_contract_terms */
    TMH_db->preflight (TMH_db->cls);
    {
      uint64_t order_serial;

      qs = TMH_db->lookup_contract_terms (TMH_db->cls,
                                          hc->instance->settings.id,
                                          order_id,
                                          &god->contract_terms,
                                          &order_serial);
    }
    if (0 > qs)
    {
      /* single, read-only SQL statements should never cause
         serialization problems */
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR != qs);
      /* Always report on hard error as well to enable diagnostics */
      GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
      return TALER_MHD_reply_with_error (connection,
                                         MHD_HTTP_INTERNAL_SERVER_ERROR,
                                         TALER_EC_GET_ORDERS_DB_LOOKUP_ERROR,
                                         "database error looking up contract");
    }

    /* Check client provided the right hash code of the contract terms */
    if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs)
    {
      struct GNUNET_HashCode h;

      if (GNUNET_OK !=
          TALER_JSON_contract_hash (god->contract_terms,
                                    &h))
      {
        GNUNET_break (0);
        GNUNET_free (god);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_INTERNAL_SERVER_ERROR,
                                           TALER_EC_INTERNAL_LOGIC_ERROR,
                                           "Could not hash contract terms");
      }
      if (0 !=
          GNUNET_memcmp (&h,
                         &god->h_contract_terms))
      {
        GNUNET_break_op (0);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_FORBIDDEN,
                                           TALER_EC_GET_ORDER_WRONG_CONTRACT,
                                           "Contract hash does not match order");
      }
    }

    if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
    {
      struct TALER_ClaimTokenP db_claim_token;

      qs = TMH_db->lookup_order (TMH_db->cls,
                                 hc->instance->settings.id,
                                 order_id,
                                 &db_claim_token,
                                 &god->contract_terms);
      if (0 > qs)
      {
        /* single, read-only SQL statements should never cause
           serialization problems */
        GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR != qs);
        /* Always report on hard error as well to enable diagnostics */
        GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_INTERNAL_SERVER_ERROR,
                                           TALER_EC_GET_ORDERS_DB_LOOKUP_ERROR,
                                           "database error looking up order");
      }
      if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs)
      {
        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                    "Unknown order id given: `%s'\n",
                    order_id);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_NOT_FOUND,
                                           TALER_EC_GET_ORDERS_ID_UNKNOWN,
                                           "order_id not found in database");
      }

      if (0 != GNUNET_memcmp (&db_claim_token,
                              &god->claim_token))
      {
        /* Token wrong */
        GNUNET_break_op (0);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_FORBIDDEN,
                                           TALER_EC_MERCHANT_GET_ORDER_INVALID_TOKEN,
                                           "Claim token invalid");
      }
      god->unclaimed = true;
    } /* end unclaimed order logic */

    {
      struct GNUNET_JSON_Specification spec[] = {
        GNUNET_JSON_spec_string ("fulfillment_url",
                                 &god->fulfillment_url),
        GNUNET_JSON_spec_end ()
      };

      if (GNUNET_OK !=
          GNUNET_JSON_parse (god->contract_terms,
                             spec,
                             NULL, NULL))
      {
        GNUNET_break (0);
        return TALER_MHD_reply_with_error (connection,
                                           MHD_HTTP_INTERNAL_SERVER_ERROR,
                                           TALER_EC_GET_ORDERS_DB_LOOKUP_ERROR,
                                           "Merchant database error (contract terms corrupted)");
      }
    }
  } /* end of first-time initialization / sanity checks */

  if (god->unclaimed)
  {
    /* Order is unclaimed, no need to check for payments or even
       refunds, simply always generate payment request */
    return send_pay_request (god,
                             NULL);
  }

  if ( (NULL != god->session_id) &&
       (NULL != god->fulfillment_url) )
  {
    /* Check if paid within a session. */
    char *already_paid_order_id = NULL;

    qs = TMH_db->lookup_order_by_fulfillment (TMH_db->cls,
                                              hc->instance->settings.id,
                                              god->fulfillment_url,
                                              god->session_id,
                                              &already_paid_order_id);
    if (qs < 0)
    {
      /* single, read-only SQL statements should never cause
         serialization problems */
      GNUNET_break (GNUNET_DB_STATUS_SOFT_ERROR != qs);
      /* Always report on hard error as well to enable diagnostics */
      GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
      return TALER_MHD_reply_with_error (connection,
                                         MHD_HTTP_INTERNAL_SERVER_ERROR,
                                         TALER_EC_GET_ORDERS_DB_LOOKUP_ERROR,
                                         "db error fetching pay session info");
    }
    if ( (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs) ||
         (0 != strcmp (order_id,
                       already_paid_order_id)) )
    {
      MHD_RESULT ret;

      ret = send_pay_request (god,
                              already_paid_order_id);
      GNUNET_free (already_paid_order_id);
      return ret;
    }
    GNUNET_break (1 == qs);
    GNUNET_free (already_paid_order_id);
  }
  else
  {
    /* Check if paid regardless of session. */
    struct GNUNET_HashCode h_contract;
    bool paid;

    qs = TMH_db->lookup_order_status (TMH_db->cls,
                                      hc->instance->settings.id,
                                      order_id,
                                      &h_contract,
                                      &paid);
    if (0 >= qs)
    {
      /* Always report on hard error as well to enable diagnostics */
      GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR == qs);
      return TALER_MHD_reply_with_error (connection,
                                         MHD_HTTP_INTERNAL_SERVER_ERROR,
                                         TALER_EC_GET_ORDERS_DB_LOOKUP_ERROR,
                                         "Merchant database error");
    }
    GNUNET_break (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT == qs);
    GNUNET_break (0 ==
                  GNUNET_memcmp (&h_contract,
                                 &god->h_contract_terms));
    if (! paid)
    {
      return send_pay_request (god,
                               NULL);
    }
  }

  /* At this point, we know the contract was paid. Let's check for
     refunds. First, clear away refunds found from previous invocations. */
  rf_cleanup (god);
  GNUNET_assert (GNUNET_OK == TALER_amount_get_zero (TMH_currency,
                                                     &god->refund_amount));
  qs = TMH_db->lookup_refunds_detailed (TMH_db->cls,
                                        hc->instance->settings.id,
                                        &god->h_contract_terms,
                                        &process_refunds_cb,
                                        god);
  if (0 > qs)
  {
    GNUNET_break (0);
    return TALER_MHD_reply_with_error (connection,
                                       MHD_HTTP_INTERNAL_SERVER_ERROR,
                                       TALER_EC_GET_ORDERS_DB_LOOKUP_ERROR,
                                       "Failed to lookup refunds for contract");
  }

  /* Now launch exchange interactions, unless we already have the
     response in the database! */
  for (struct CoinRefund *cr = god->cr_head;
       NULL != cr;
       cr = cr->next)
  {
    enum GNUNET_DB_QueryStatus qs;

    qs = TMH_db->lookup_refund_proof (TMH_db->cls,
                                      cr->refund_serial,
                                      &cr->exchange_sig,
                                      &cr->exchange_pub);
    switch (qs)
    {
    case GNUNET_DB_STATUS_HARD_ERROR:
    case GNUNET_DB_STATUS_SOFT_ERROR:
      return TALER_MHD_reply_with_error (connection,
                                         MHD_HTTP_INTERNAL_SERVER_ERROR,
                                         TALER_EC_GET_ORDERS_DB_LOOKUP_ERROR,
                                         "Merchant database error");
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      /* We need to talk to the exchange */
      cr->fo = TMH_EXCHANGES_find_exchange (cr->exchange_url,
                                            NULL,
                                            GNUNET_NO,
                                            &exchange_found_cb,
                                            cr);
      break;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      /* We got a reply earlier, set status accordingly */
      cr->exchange_status = MHD_HTTP_OK;
      break;
    }
  }

  if ( (god->sc.awaiting_refund) &&
       ( (! god->refunded) ||
         (1 != TALER_amount_cmp (&god->refund_amount,
                                 &god->sc.refund_expected)) ) )
  {
    /* Client is waiting for a refund larger than what we have, suspend
       until timeout */
    struct GNUNET_TIME_Relative remaining;

    remaining = GNUNET_TIME_absolute_get_remaining (god->sc.long_poll_timeout);
    if (0 != remaining.rel_value_us)
    {
      /* yes, indeed suspend */
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Awaiting refund exceeding %s\n",
                  TALER_amount2s (&god->sc.refund_expected));
      suspend_god (god);
      return MHD_YES;
    }
  }

  /* Check if there are still exchange operations pending */
  if (god_pending (god))
  {
    if (! god->suspended)
    {
      god->suspended = true;
      MHD_suspend_connection (connection);
      GNUNET_CONTAINER_DLL_insert (god_head,
                                   god_tail,
                                   god);
    }
    return MHD_YES;   /* we're still talking to the exchange */
  }

  /* All operations done, build final response */
  {
    json_t *ra;

    ra = json_array ();
    GNUNET_assert (NULL != ra);
    for (struct CoinRefund *cr = god->cr_head;
         NULL != cr;
         cr = cr->next)
    {
      json_t *refund;

      if (MHD_HTTP_OK != cr->exchange_status)
      {
        if (NULL == cr->exchange_reply)
        {
          refund = json_pack ("{s:s, s:I,s:I,s:o,s:o,s:o}"
                              "type",
                              "failure",
                              "exchange_status",
                              (json_int_t) cr->exchange_status,
                              "rtransaction_id",
                              (json_int_t) cr->rtransaction_id,
                              "coin_pub",
                              GNUNET_JSON_from_data_auto (&cr->coin_pub),
                              "refund_amount",
                              TALER_JSON_from_amount (&cr->refund_amount),
                              "execution_time",
                              GNUNET_JSON_from_time_abs (cr->execution_time));
        }
        else
        {
          refund = json_pack ("{s:s,s:I,s:I,s:o,s:I,s:o,s:o,s:o}"
                              "type",
                              "failure",
                              "exchange_status",
                              (json_int_t) cr->exchange_status,
                              "exchange_code",
                              (json_int_t) cr->exchange_code,
                              "exchange_reply",
                              cr->exchange_reply,
                              "rtransaction_id",
                              (json_int_t) cr->rtransaction_id,
                              "coin_pub",
                              GNUNET_JSON_from_data_auto (&cr->coin_pub),
                              "refund_amount",
                              TALER_JSON_from_amount (&cr->refund_amount),
                              "execution_time",
                              GNUNET_JSON_from_time_abs (cr->execution_time));
        }
      }
      else
      {
        refund = json_pack ("{s:s,s:I,s:o,s:o,s:I,s:o,s:o,s:o}",
                            "type",
                            "success",
                            "exchange_status",
                            (json_int_t) cr->exchange_status,
                            "exchange_sig",
                            GNUNET_JSON_from_data_auto (&cr->exchange_sig),
                            "exchange_pub",
                            GNUNET_JSON_from_data_auto (&cr->exchange_pub),
                            "rtransaction_id",
                            (json_int_t) cr->rtransaction_id,
                            "coin_pub",
                            GNUNET_JSON_from_data_auto (&cr->coin_pub),
                            "refund_amount",
                            TALER_JSON_from_amount (&cr->refund_amount),
                            "execution_time",
                            GNUNET_JSON_from_time_abs (cr->execution_time));
      }
      GNUNET_assert (
        0 ==
        json_array_append_new (ra,
                               refund));
    }

    if (god->generate_html)
    {
      int ret;
      struct MHD_Response *reply;
      char *body;
      size_t body_size;
      char *qr;

      qr = create_qrcode ("taler://refund/FIXME");
      if (NULL == qr)
      {
        GNUNET_break (0);
        return MHD_NO; // FIXME: add nicer error reply...
      }

      if (god->refunded)
      {
        struct KVC kvc[] = {
          { "refund_amount",
            GNUNET_strdup (TALER_amount2s (&god->refund_amount)) },
          { "refund_uri",
            qr },
          { NULL, NULL }
        };
        const char *tmpl;

        tmpl = load_template ("offer_refund");
        if (NULL == tmpl)
        {
          GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                      "Failed to load template `%s'\n",
                      "offer_refund");
          return MHD_NO; // FIXME: add nicer error reply...
        }
        if (0 !=
            mustach (tmpl,
                     &itf,
                     &kvc,
                     &body,
                     &body_size))
        {
          GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                               "mustach");
          return MHD_NO; // FIXME: add nicer error reply...
        }
      }
      else
      {
        struct KVC kvc[] = {
          { NULL, NULL }
        };
        const char *tmpl;

        tmpl = load_template ("show_order_details");
        if (NULL == tmpl)
        {
          GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                      "Failed to load template `%s'\n",
                      "show_order_details");
          return MHD_NO; // FIXME: add nicer error reply...
        }
        if (0 !=
            mustach (tmpl,
                     &itf,
                     &kvc,
                     &body,
                     &body_size))
        {
          GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                               "mustach");
          return MHD_NO; // FIXME: add nicer error reply...
        }
      }
      reply = MHD_create_response_from_buffer (body_size,
                                               body,
                                               MHD_RESPMEM_MUST_FREE);
      if (NULL == reply)
      {
        GNUNET_break (0);
        return MHD_NO;
      }
      GNUNET_break (MHD_NO !=
                    MHD_add_response_header (reply,
                                             MHD_HTTP_HEADER_CONTENT_TYPE,
                                             "text/html"));
      ret = MHD_queue_response (god->sc.con,
                                MHD_HTTP_OK,
                                reply);
      MHD_destroy_response (reply);
      return ret;
    }
    else
    {
      return TALER_MHD_reply_json_pack (
        connection,
        MHD_HTTP_OK,
        "{s:b, s:o, s:o, s:o}",
        "refunded", god->refunded,
        "refund_amount",
        TALER_JSON_from_amount (&god->refund_amount),
        "refunds",
        ra,
        "merchant_pub",
        GNUNET_JSON_from_data_auto (&hc->instance->merchant_pub));
    }
  }
}


/**
 * Nicely shut down.
 */
void __attribute__ ((destructor))
get_orders_fini ()
{
  for (unsigned int i = 0; i<loaded_length; i++)
    GNUNET_free (loaded[i].value);
}


/* end of taler-merchant-httpd_get-orders-ID.c */