summaryrefslogtreecommitdiffstats
path: root/auth_mellon_handler.c
blob: 2a0bd741277fb0a986acbf3a72d4c37e01d6827e (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
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
/*
 *
 *   auth_mellon_handler.c: an authentication apache module
 *   Copyright  2003-2007 UNINETT (http://www.uninett.no/)
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program 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 this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */


#include "auth_mellon.h"


#ifdef HAVE_lasso_server_new_from_buffers
#  define SERVER_NEW lasso_server_new_from_buffers
#else /* HAVE_lasso_server_new_from_buffers */
#  define SERVER_NEW lasso_server_new
#endif /* HAVE_lasso_server_new_from_buffers */



#ifdef HAVE_lasso_server_new_from_buffers
/* This function generates optional metadata for a given element
 *
 * Parameters:
 *  apr_pool_t *p        Pool to allocate memory from
 *  apr_hash_t *t        Hash of lang -> strings
 *  const char *e        Name of the element
 *
 * Returns:
 *  the metadata, or NULL if an error occured
 */
static char *am_optional_metadata_element(apr_pool_t *p,
                                          apr_hash_t *h,
                                          const char *e)
{
    apr_hash_index_t *index;
    char *data = "";

    for (index = apr_hash_first(p, h); index; index = apr_hash_next(index)) {
        char *lang;
        char *value;
        apr_ssize_t slen;
	char *xmllang = "";

        apr_hash_this(index, (const void **)&lang, &slen, (void *)&value);
        
        if (*lang != '\0')
            xmllang = apr_psprintf(p, " xml:lang=\"%s\"", lang);

        data = apr_psprintf(p, "%s<%s%s>%s</%s>",
                            data, e, xmllang, value, e);
    }

    return data;
}

/* This function generates optinal metadata
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  the metadata, or NULL if an error occured
 */
static char *am_optional_metadata(apr_pool_t *p, request_rec *r)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    int count = 0;
    char *org_data = NULL;
    char *org_name = NULL;
    char *org_display_name = NULL;
    char *org_url = NULL;

    count += apr_hash_count(cfg->sp_org_name);
    count += apr_hash_count(cfg->sp_org_display_name);
    count += apr_hash_count(cfg->sp_org_url);

    if (count == 0) 
        return "";

    org_name = am_optional_metadata_element(p, cfg->sp_org_name,
                                            "OrganizationName");
    org_display_name = am_optional_metadata_element(p, cfg->sp_org_display_name,
                                                    "OrganizationDisplayName");
    org_url = am_optional_metadata_element(p, cfg->sp_org_url,
                                           "OrganizationURL");
    org_data = apr_psprintf(p, "<Organization>%s%s%s</Organization>",
                            org_name, org_display_name, org_url);

    return org_data;
}


/* This function generates metadata
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  the metadata, or NULL if an error occured
 */
static char *am_generate_metadata(apr_pool_t *p, request_rec *r)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    char *url = am_get_endpoint_url(r);
    char *cert = "";
    const char *sp_entity_id;

    sp_entity_id = cfg->sp_entity_id ? cfg->sp_entity_id : url;

    if (cfg->sp_cert_file) {
	char *sp_cert_file;
        char *cp;
        char *bp;
        const char *begin = "-----BEGIN CERTIFICATE-----";
        const char *end = "-----END CERTIFICATE-----";

        /* 
         * Try to remove leading and trailing garbage, as it can
         * wreak havoc XML parser if it contains [<>&]
         */
	sp_cert_file = apr_pstrdup(p, cfg->sp_cert_file);

        cp = strstr(sp_cert_file, begin);
        if (cp != NULL) 
            sp_cert_file = cp + strlen(begin);

        cp = strstr(sp_cert_file, end);
        if (cp != NULL)
            *cp = '\0';
        
	/* 
	 * And remove any non printing char (CR, spaces...)
	 */
	bp = sp_cert_file;
	for (cp = sp_cert_file; *cp; cp++) {
		if (apr_isgraph(*cp))
			*bp++ = *cp;
	}
	*bp = '\0';

        cert = apr_psprintf(p,
          "<KeyDescriptor use=\"signing\">"
            "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">"
              "<ds:X509Data>"
                "<ds:X509Certificate>%s</ds:X509Certificate>"
              "</ds:X509Data>"
            "</ds:KeyInfo>"
          "</KeyDescriptor>"
          "<KeyDescriptor use=\"encryption\">"
            "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">"
              "<ds:X509Data>"
                "<ds:X509Certificate>%s</ds:X509Certificate>"
              "</ds:X509Data>"
            "</ds:KeyInfo>"
          "</KeyDescriptor>",
          sp_cert_file,
          sp_cert_file);
    }

    return apr_psprintf(p,
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
<EntityDescriptor\n\
 entityID=\"%s%s\"\n\
 xmlns=\"urn:oasis:names:tc:SAML:2.0:metadata\">\n\
 <SPSSODescriptor\n\
   AuthnRequestsSigned=\"true\"\n\
   WantAssertionsSigned=\"true\"\n\
   protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\">\n\
   %s\
   <SingleLogoutService\n\
     Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:SOAP\"\n\
     Location=\"%slogout\" />\n\
   <SingleLogoutService\n\
     Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\"\n\
     Location=\"%slogout\" />\n\
   <NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</NameIDFormat>\n\
   <AssertionConsumerService\n\
     index=\"0\"\n\
     isDefault=\"true\"\n\
     Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"\n\
     Location=\"%spostResponse\" />\n\
   <AssertionConsumerService\n\
     index=\"1\"\n\
     Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact\"\n\
     Location=\"%sartifactResponse\" />\n\
 </SPSSODescriptor>\n\
 %s\n\
</EntityDescriptor>",
      sp_entity_id, cfg->sp_entity_id ? "" : "metadata", 
      cert, url, url, url, url, am_optional_metadata(p, r));
}
#endif /* HAVE_lasso_server_new_from_buffers */


/*
 * This function loads all IdP metadata in a lasso server
 *
 * Parameters:
 *  am_dir_cfg_rec *cfg  The server configuration.
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  number of loaded providers
 */
static guint am_server_add_providers(am_dir_cfg_rec *cfg, request_rec *r)
{
    apr_size_t index;

#ifndef HAVE_lasso_server_load_metadata
    const char *idp_public_key_file;

    if (cfg->idp_metadata->nelts == 1)
        idp_public_key_file = cfg->idp_public_key_file;
    else
        idp_public_key_file = NULL;
#endif /* ! HAVE_lasso_server_load_metadata */

    for (index = 0; index < cfg->idp_metadata->nelts; index++) {
        const am_metadata_t *idp_metadata;
        int error;
#ifdef HAVE_lasso_server_load_metadata
        GList *loaded_idp = NULL;
#endif /* HAVE_lasso_server_load_metadata */

        idp_metadata = &( ((const am_metadata_t*)cfg->idp_metadata->elts) [index] );

#ifdef HAVE_lasso_server_load_metadata
        error = lasso_server_load_metadata(cfg->server,
                                           LASSO_PROVIDER_ROLE_IDP,
                                           idp_metadata->file,
                                           idp_metadata->chain,
                                           cfg->idp_ignore,
                                           &loaded_idp,
                                           LASSO_SERVER_LOAD_METADATA_FLAG_DEFAULT);
        if (error == 0) {
            GList *idx;

            for (idx = loaded_idp; idx != NULL; idx = idx->next) {
                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                               "loaded IdP \"%s\" from \"%s\".",
                               (char *)idx->data, idp_metadata->file);
            }
        }

        if (loaded_idp != NULL) {
            for (GList *idx = loaded_idp; idx != NULL; idx = idx->next) {
                g_free(idx->data);
            }
            g_list_free(loaded_idp);
        }

#else /* HAVE_lasso_server_load_metadata */
        error = lasso_server_add_provider(cfg->server,
                                          LASSO_PROVIDER_ROLE_IDP,
                                          idp_metadata->file,
                                          idp_public_key_file,
                                          cfg->idp_ca_file);
#endif /* HAVE_lasso_server_load_metadata */

        if (error != 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Error adding metadata \"%s\" to "
                          "lasso server objects: %s.",
                          idp_metadata->file, lasso_strerror(error));
        }
    }

    return g_hash_table_size(cfg->server->providers);
}


static LassoServer *am_get_lasso_server(request_rec *r)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);

    cfg = cfg->inherit_server_from;

    apr_thread_mutex_lock(cfg->server_mutex);
    if(cfg->server == NULL) {
        if(cfg->sp_metadata_file == NULL) {

#ifdef HAVE_lasso_server_new_from_buffers
            /*
             * Try to generate missing metadata
             */
            apr_pool_t *pool = r->server->process->pconf;
            cfg->sp_metadata_file = am_generate_metadata(pool, r);
#else
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Missing MellonSPMetadataFile option.");
            apr_thread_mutex_unlock(cfg->server_mutex);
            return NULL;
#endif /* HAVE_lasso_server_new_from_buffers */
        }

        cfg->server = SERVER_NEW(cfg->sp_metadata_file,
                                 cfg->sp_private_key_file,
                                 NULL,
                                 cfg->sp_cert_file);
        if(cfg->server == NULL) {
	    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
			  "Error initializing lasso server object. Please"
			  " verify the following configuration directives:"
			  " MellonSPMetadataFile and MellonSPPrivateKeyFile.");

	    apr_thread_mutex_unlock(cfg->server_mutex);
	    return NULL;
	}

        if (am_server_add_providers(cfg, r) == 0) {
	    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
			  "Error adding IdP to lasso server object. Please"
			  " verify the following configuration directives:"
			  " MellonIdPMetadataFile and"
                          " MellonIdPPublicKeyFile.");

	    lasso_server_destroy(cfg->server);
	    cfg->server = NULL;

	    apr_thread_mutex_unlock(cfg->server_mutex);
	    return NULL;
	}
    }

    apr_thread_mutex_unlock(cfg->server_mutex);

    return cfg->server;
}


/* Redirect to discovery service.
 *
 * Parameters:
 *  request_rec *r         The request we received.
 *  const char *return_to  The URL the user should be returned to after login.
 *
 * Returns:
 *  HTTP_SEE_OTHER on success, an error otherwise.
 */
static int am_start_disco(request_rec *r, const char *return_to)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    const char *endpoint = am_get_endpoint_url(r);
    LassoServer *server;
    const char *sp_entity_id;
    const char *sep;
    const char *login_url;
    const char *discovery_url;

    server = am_get_lasso_server(r);
    if(server == NULL) {
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    sp_entity_id = LASSO_PROVIDER(server)->ProviderID;

    login_url = apr_psprintf(r->pool, "%slogin?ReturnTo=%s",
                             endpoint,
                             am_urlencode(r->pool, return_to));
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                  "login_url = %s", login_url);

    /* If discovery URL already has a ? we append a & */
    sep = (strchr(cfg->discovery_url, '?')) ? "&" : "?";

    discovery_url = apr_psprintf(r->pool, "%s%sentityID=%s&"
                                 "return=%s&returnIDParam=IdP",
                                 cfg->discovery_url, sep,
                                 am_urlencode(r->pool, sp_entity_id),
                                 am_urlencode(r->pool, login_url));

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                  "discovery_url = %s", discovery_url);
    apr_table_setn(r->headers_out, "Location", discovery_url);
    return HTTP_SEE_OTHER;
}


/* This function returns the first configured IdP
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  the providerID, or NULL if an error occured
 */
static const char *am_first_idp(request_rec *r)
{
    LassoServer *server;
    GList *idp_list;
    const char *idp_providerid;

    server = am_get_lasso_server(r);
    if (server == NULL)
        return NULL;

    idp_list = g_hash_table_get_keys(server->providers);
    if (idp_list == NULL)
      return NULL;

    idp_providerid = idp_list->data;

    g_list_free(idp_list);

    return idp_providerid;
}


/* This function selects an IdP and returns its provider_id
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  the provider_id, or NULL if an error occured
 */
static const char *am_get_idp(request_rec *r)
{
    LassoServer *server;
    const char *idp_provider_id;

    server = am_get_lasso_server(r);
    if (server == NULL)
        return NULL;

    /*
     * If we have a single IdP, return that one.
     */
    if (g_hash_table_size(server->providers) == 1)
        return am_first_idp(r);

    /*
     * If IdP discovery handed us an IdP, try to use it.
     */
    idp_provider_id = am_extract_query_parameter(r->pool, r->args, "IdP");
    if (idp_provider_id != NULL) {
        int rc;

        rc = am_urldecode((char *)idp_provider_id);
        if (rc != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                          "Could not urldecode IdP discovery value.");
            idp_provider_id = NULL;
        } else {
            if (g_hash_table_lookup(server->providers, idp_provider_id) == NULL)
                idp_provider_id = NULL;
        }

        /*
         * If we do not know about it, fall back to default.
         */
        if (idp_provider_id == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                          "IdP discovery returned unknown or inexistant IdP");
            idp_provider_id = am_first_idp(r);
        }

        return idp_provider_id;
    }

    /*
     * No IdP answered, use default
     * Perhaps we should redirect to an error page instead.
     */
    return am_first_idp(r);
}


/* This function stores dumps of the LassoIdentity and LassoSession objects
 * for the given LassoProfile object. The dumps are stored in the session
 * belonging to the current request.
 *
 * Parameters:
 *  request_rec *r             The current request.
 *  am_cache_entry_t *session  The session we are creating.
 *  LassoProfile *profile      The profile object.
 *  char *saml_response        The full SAML 2.0 response message.
 *
 * Returns:
 *  OK on success or HTTP_INTERNAL_SERVER_ERROR on failure.
 */
static int am_save_lasso_profile_state(request_rec *r,
                                       am_cache_entry_t *session,
                                       LassoProfile *profile,
                                       char *saml_response)
{
    LassoIdentity *lasso_identity;
    LassoSession *lasso_session;
    gchar *identity_dump;
    gchar *session_dump;
    int ret;

    lasso_identity = lasso_profile_get_identity(profile);
    if(lasso_identity == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "The current LassoProfile object doesn't contain a"
                      " LassoIdentity object.");
        identity_dump = NULL;
    } else {
        identity_dump = lasso_identity_dump(lasso_identity);
        if(identity_dump == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Could not create a identity dump from the"
                          " LassoIdentity object.");
            return HTTP_INTERNAL_SERVER_ERROR;
        }
    }

    lasso_session = lasso_profile_get_session(profile);
    if(lasso_session == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "The current LassoProfile object doesn't contain a"
                      " LassoSession object.");
        session_dump = NULL;
    } else {
        session_dump = lasso_session_dump(lasso_session);
        if(session_dump == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Could not create a session dump from the"
                          " LassoSession object.");
            if(identity_dump != NULL) {
                g_free(identity_dump);
            }
            return HTTP_INTERNAL_SERVER_ERROR;
        }
    }


    /* Save the profile state. */
    ret = am_cache_set_lasso_state(session,
                                   identity_dump,
                                   session_dump,
                                   saml_response);

    if(identity_dump != NULL) {
        g_free(identity_dump);
    }

    if(session_dump != NULL) {
        g_free(session_dump);
    }

    return ret;
}


/* Returns a SAML response
 *
 * Parameters:
 *  request_rec *r         The current request.
 *  LassoProfile *profile  The profile object.
 *
 * Returns:
 *  HTTP_INTERNAL_SERVER_ERROR if an error occurs, HTTP_SEE_OTHER for the
 *  Redirect binding and OK for the SOAP binding.
 */
static int am_return_logout_response(request_rec *r,
                              LassoProfile *profile)
{
    if (profile->msg_url && profile->msg_body) {
        /* POST binding response */
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error building logout response message."
                      " POST binding is unsupported.");
        return HTTP_INTERNAL_SERVER_ERROR;
    } else if (profile->msg_url) {
        /* HTTP-Redirect binding response */
        apr_table_setn(r->headers_out, "Location",
                       apr_pstrdup(r->pool, profile->msg_url));
        return HTTP_SEE_OTHER;
    } else if (profile->msg_body) {
        /* SOAP binding response */
        ap_set_content_type(r, "text/xml");
        ap_rputs(profile->msg_body, r);
        return OK;
    } else {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error building logout response message."
                      " There is no content to return.");
        return HTTP_INTERNAL_SERVER_ERROR;
    }
}


/* This function restores dumps of a LassoIdentity object and a LassoSession
 * object. The dumps are fetched from the session belonging to the current
 * request and restored to the given LassoProfile object.
 *
 * Parameters:
 *  request_rec *r         The current request.
 *  LassoProfile *profile  The profile object.
 *  am_cache_entry_t *am_session The session structure.
 *
 * Returns:
 *  OK on success or HTTP_INTERNAL_SERVER_ERROR on failure.
 */
static void am_restore_lasso_profile_state(request_rec *r, 
                                           LassoProfile *profile,
                                           am_cache_entry_t *am_session)
{
    const char *identity_dump;
    const char *session_dump;
    int rc;


    if(am_session == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Could not get auth_mellon session while attempting"
                      " to restore the lasso profile state.");
        return;
    }

    identity_dump = am_cache_get_lasso_identity(am_session);
    if(identity_dump != NULL) {
        rc = lasso_profile_set_identity_from_dump(profile, identity_dump);
        if(rc < 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Could not restore identity from dump."
                          " Lasso error: [%i] %s", rc, lasso_strerror(rc));
            am_release_request_session(r, am_session);
        }
    }

    session_dump = am_cache_get_lasso_session(am_session);
    if(session_dump != NULL) {
        rc = lasso_profile_set_session_from_dump(profile, session_dump);
        if(rc < 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Could not restore session from dump."
                          " Lasso error: [%i] %s", rc, lasso_strerror(rc));
            am_release_request_session(r, am_session);
        }
    }
}

/* This function handles an IdP initiated logout request.
 *
 * Parameters:
 *  request_rec *r       The logout request.
 *  LassoLogout *logout  A LassoLogout object initiated with
 *                       the current session.
 *
 * Returns:
 *  OK on success, or an error if any of the steps fail.
 */
static int am_handle_logout_request(request_rec *r, 
                                    LassoLogout *logout, char *msg)
{
    gint res = 0, rc = HTTP_OK;
    am_cache_entry_t *session = NULL;
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);

    /* Process the logout message. Ignore missing signature. */
    res = lasso_logout_process_request_msg(logout, msg);
#ifdef HAVE_lasso_profile_set_signature_verify_hint
    if(res != 0 && res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND) {
        if (apr_hash_get(cfg->do_not_verify_logout_signature,
                         logout->parent.remote_providerID,
                         APR_HASH_KEY_STRING)) {
            lasso_profile_set_signature_verify_hint(&logout->parent,
                LASSO_PROFILE_SIGNATURE_VERIFY_HINT_IGNORE);
            res = lasso_logout_process_request_msg(logout, msg);
        }
    }
#endif
    if(res != 0 && res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error processing logout request message."
                      " Lasso error: [%i] %s", res, lasso_strerror(res));

        rc = HTTP_BAD_REQUEST;
        goto exit;
    }

    /* Search session using NameID */
    if (! LASSO_IS_SAML2_NAME_ID(logout->parent.nameIdentifier)) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error processing logout request message."
                      " No NameID found");
        rc = HTTP_BAD_REQUEST;
        goto exit;
    }
    session = am_get_request_session_by_nameid(r,
                    ((LassoSaml2NameID*)logout->parent.nameIdentifier)->content);
    if (session == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error processing logout request message."
                      " No session found for NameID %s",
                      ((LassoSaml2NameID*)logout->parent.nameIdentifier)->content);

    }
    if (session == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error processing logout request message."
                      " No session found.");

    } else {
        am_restore_lasso_profile_state(r, &logout->parent, session);
    }

    /* Validate the logout message. Ignore missing signature. */
    res = lasso_logout_validate_request(logout);
    if(res != 0 && 
       res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND &&
       res != LASSO_PROFILE_ERROR_SESSION_NOT_FOUND) {
        ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                      "Error validating logout request."
                      " Lasso error: [%i] %s", res, lasso_strerror(res));
        rc = HTTP_INTERNAL_SERVER_ERROR;
        goto exit;
    }
    /* We continue with the logout despite those errors. They could be
     * caused by the IdP believing that we are logged in when we are not.
     */

    if (session != NULL && res != LASSO_PROFILE_ERROR_SESSION_NOT_FOUND) {
        /* We found a matching session -- delete it. */
        am_delete_request_session(r, session);
        session = NULL;
    }

    /* Create response message. */
    res = lasso_logout_build_response_msg(logout);
    if(res != 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error building logout response message."
                      " Lasso error: [%i] %s", res, lasso_strerror(res));

        rc = HTTP_INTERNAL_SERVER_ERROR;
        goto exit;
    }
    rc = am_return_logout_response(r, &logout->parent);

exit:
    if (session != NULL) {
        am_release_request_session(r, session);
    }

    lasso_logout_destroy(logout);
    return rc;
}


/* This function handles a logout response message from the IdP. We get
 * this message after we have sent a logout request to the IdP.
 *
 * Parameters:
 *  request_rec *r       The logout response request.
 *  LassoLogout *logout  A LassoLogout object initiated with
 *                       the current session.
 *
 * Returns:
 *  OK on success, or an error if any of the steps fail.
 */
static int am_handle_logout_response(request_rec *r, LassoLogout *logout)
{
    gint res;
    int rc;
    am_cache_entry_t *session;
    char *return_to;
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);

    res = lasso_logout_process_response_msg(logout, r->args);
#ifdef HAVE_lasso_profile_set_signature_verify_hint
    if(res != 0 && res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND) {
        if (apr_hash_get(cfg->do_not_verify_logout_signature,
                         logout->parent.remote_providerID,
                         APR_HASH_KEY_STRING)) {
            lasso_profile_set_signature_verify_hint(&logout->parent,
                LASSO_PROFILE_SIGNATURE_VERIFY_HINT_IGNORE);
            res = lasso_logout_process_response_msg(logout, r->args);
        }
    }
#endif
    if(res != 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Unable to process logout response."
                      " Lasso error: [%i] %s", res, lasso_strerror(res));

        lasso_logout_destroy(logout);
        return HTTP_BAD_REQUEST;
    }

    lasso_logout_destroy(logout);

    /* Delete the session. */
    session = am_get_request_session(r);
    if(session != NULL) {
        am_delete_request_session(r, session);
    }

    return_to = am_extract_query_parameter(r->pool, r->args, "RelayState");
    if(return_to == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "No RelayState parameter to logout response handler."
                      " It is possible that your IdP doesn't support the"
                      " RelayState parameter.");
        return HTTP_BAD_REQUEST;
    }

    rc = am_urldecode(return_to);
    if(rc != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                      "Could not urldecode RelayState value in logout"
                      " response.");
        return HTTP_BAD_REQUEST;
    }

    /* Check for bad characters in RelayState. */
    rc = am_check_url(r, return_to);
    if (rc != OK) {
        return rc;
    }

    apr_table_setn(r->headers_out, "Location", return_to);
    return HTTP_SEE_OTHER;
}


/* This function initiates a logout request and sends it to the IdP.
 *
 * Parameters:
 *  request_rec *r       The logout response request.
 *  LassoLogout *logout  A LassoLogout object initiated with
 *                       the current session.
 *
 * Returns:
 *  OK on success, or an error if any of the steps fail.
 */
static int am_init_logout_request(request_rec *r, LassoLogout *logout)
{
    char *return_to;
    int rc;
    am_cache_entry_t *mellon_session;
    gint res;
    char *redirect_to;
    LassoProfile *profile;
    LassoSession *session;
    GList *assertion_list;
    LassoNode *assertion_n;
    LassoSaml2Assertion *assertion;
    LassoSaml2AuthnStatement *authnStatement;
    LassoSamlp2LogoutRequest *request;

    return_to = am_extract_query_parameter(r->pool, r->args, "ReturnTo");
    rc = am_urldecode(return_to);
    if (rc != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                      "Could not urldecode ReturnTo value.");
        return HTTP_BAD_REQUEST;
    }

    /* Disable the the local session (in case the IdP doesn't respond). */
    mellon_session = am_get_request_session(r);
    if(mellon_session != NULL) {
        am_restore_lasso_profile_state(r, &logout->parent, mellon_session);
        mellon_session->logged_in = 0;
        am_release_request_session(r, mellon_session);
    }

    /* Create the logout request message. */
    res = lasso_logout_init_request(logout, NULL, LASSO_HTTP_METHOD_REDIRECT);
    /* Early non failing return. */
    if (res != 0) {
        if(res == LASSO_PROFILE_ERROR_SESSION_NOT_FOUND) {
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                          "User attempted to initiate logout without being"
                          " loggged in.");
        } else if (res == LASSO_LOGOUT_ERROR_UNSUPPORTED_PROFILE || res == LASSO_PROFILE_ERROR_UNSUPPORTED_PROFILE) {
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "Current identity provider "
                            "does not support single logout. Destroying local session only.");

        } else if(res != 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Unable to create logout request."
                          " Lasso error: [%i] %s", res, lasso_strerror(res));

            lasso_logout_destroy(logout);
            return HTTP_INTERNAL_SERVER_ERROR;
        }
        lasso_logout_destroy(logout);
        /* Check for bad characters in ReturnTo. */
        rc = am_check_url(r, return_to);
        if (rc != OK) {
            return rc;
        }
        /* Redirect to the page the user should be sent to after logout. */
        apr_table_setn(r->headers_out, "Location", return_to);
        return HTTP_SEE_OTHER;
    }

    profile = LASSO_PROFILE(logout);

    /* We need to set the SessionIndex in the LogoutRequest to the SessionIndex
     * we received during the login operation. This is not needed since release
     * 2.3.0.
     */
    if (lasso_check_version(2, 3, 0, LASSO_CHECK_VERSION_NUMERIC) == 0) {
        session = lasso_profile_get_session(profile);
        assertion_list = lasso_session_get_assertions(
            session, profile->remote_providerID);
        if(! assertion_list ||
                        LASSO_IS_SAML2_ASSERTION(assertion_list->data) == FALSE) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "No assertions found for the current session.");
            lasso_logout_destroy(logout);
            return HTTP_INTERNAL_SERVER_ERROR;
        }
        /* We currently only look at the first assertion in the list
         * lasso_session_get_assertions returns.
         */
        assertion_n = assertion_list->data;

        assertion = LASSO_SAML2_ASSERTION(assertion_n);

        /* We assume that the first authnStatement contains the data we want. */
        authnStatement = LASSO_SAML2_AUTHN_STATEMENT(assertion->AuthnStatement->data);

        if(!authnStatement) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "No AuthnStatement found in the current assertion.");
            lasso_logout_destroy(logout);
            return HTTP_INTERNAL_SERVER_ERROR;
        }

        if(authnStatement->SessionIndex) {
            request = LASSO_SAMLP2_LOGOUT_REQUEST(profile->request);
            request->SessionIndex = g_strdup(authnStatement->SessionIndex);
        }
    }


    /* Set the RelayState parameter to the return url (if we have one). */
    if(return_to) {
        profile->msg_relayState = g_strdup(return_to);
    }

    /* Serialize the request message into a url which we can redirect to. */
    res = lasso_logout_build_request_msg(logout);
    if(res != 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Unable to serialize lasso logout message."
                      " Lasso error: [%i] %s", res, lasso_strerror(res));

        lasso_logout_destroy(logout);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Set the redirect url. */
    redirect_to = apr_pstrdup(r->pool, LASSO_PROFILE(logout)->msg_url);

    /* Check if the lasso library added the RelayState. If lasso didn't add
     * a RelayState parameter, then we add one ourself. This should hopefully
     * be removed in the future.
     */
    if(return_to != NULL
       && strstr(redirect_to, "&RelayState=") == NULL
       && strstr(redirect_to, "?RelayState=") == NULL) {
        /* The url didn't contain the relaystate parameter. */
        redirect_to = apr_pstrcat(
            r->pool, redirect_to, "&RelayState=",
            am_urlencode(r->pool, return_to),
            NULL
            );
    }

    apr_table_setn(r->headers_out, "Location", redirect_to);

    lasso_logout_destroy(logout);

    /* Redirect (without including POST data if this was a POST request. */
    return HTTP_SEE_OTHER;
}


/* This function handles requests to the logout handler.
 *
 * Parameters:
 *  request_rec *r       The request.
 *
 * Returns:
 *  OK on success, or an error if any of the steps fail.
 */
static int am_handle_logout(request_rec *r)
{
    LassoServer *server;
    LassoLogout *logout;

    server = am_get_lasso_server(r);
    if(server == NULL) {
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    logout = lasso_logout_new(server);
    if(logout == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error creating lasso logout object.");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Check which type of request to the logout handler this is.
     * We have three types:
     * - logout requests: The IdP sends a logout request to this service.
     *                    it can be either through HTTP-Redirect or SOAP.
     * - logout responses: We have sent a logout request to the IdP, and
     *   are receiving a response.
     * - We want to initiate a logout request.
     */

    /* First check for IdP-initiated SOAP logout request */
    if ((r->args == NULL) && (r->method_number == M_POST)) {
        int rc;
        char *post_data;

        rc = am_read_post_data(r, &post_data, NULL);
        if (rc != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                          "Error reading POST data.");
            return HTTP_INTERNAL_SERVER_ERROR;
        }
        return am_handle_logout_request(r, logout, post_data);

    } else if(am_extract_query_parameter(r->pool, r->args, 
                                         "SAMLRequest") != NULL) {
        /* SAMLRequest - logout request from the IdP. */
        return am_handle_logout_request(r, logout, r->args);

    } else if(am_extract_query_parameter(r->pool, r->args, 
                                         "SAMLResponse") != NULL) {
        /* SAMLResponse - logout response from the IdP. */
        return am_handle_logout_response(r, logout);

    } else if(am_extract_query_parameter(r->pool, r->args, 
                                         "ReturnTo") != NULL) {
        /* RedirectTo - SP initiated logout. */
        return am_init_logout_request(r, logout);

    } else {
        /* Unknown request to the logout handler. */
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "No known parameters passed to the logout"
                      " handler. Query string was \"%s\". To initiate"
                      " a logout, you need to pass a \"ReturnTo\""
                      " parameter with a url to the web page the user should"
                      " be redirected to after a successful logout.",
                      r->args);
        return HTTP_BAD_REQUEST;
    }
}


/* This function parses a timestamp for a SAML 2.0 condition.
 *
 * Parameters:
 *  request_rec *r          The current request. Used for logging of errors.
 *  const char *timestamp   The timestamp we should parse. Must be on
 *                          the following format: "YYYY-MM-DDThh:mm:ssZ"
 *
 * Returns:
 *  An apr_time_t value with the timestamp, or 0 on error.
 */
static apr_time_t am_parse_timestamp(request_rec *r, const char *timestamp)
{
    size_t len;
    int i;
    char c;
    const char *expected;
    apr_time_exp_t time_exp;
    apr_time_t res;
    apr_status_t rc;

    len = strlen(timestamp);

    /* Verify length of timestamp. */
    if(len < 20){
        ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                      "Invalid length of timestamp: \"%s\".", timestamp);
    }

    /* Verify components of timestamp. */
    for(i = 0; i < len - 1; i++) {
        c = timestamp[i];

        expected = NULL;

        switch(i) {

        case 4:
        case 7:
            /* Matches "    -  -            " */
            if(c != '-') {
                expected = "'-'";
            }
            break;

        case 10:
            /* Matches "          T         " */
            if(c != 'T') {
                expected = "'T'";
            }
            break;

        case 13:
        case 16:
            /* Matches "             :  :   " */
            if(c != ':') {
                expected = "':'";
            }
            break;

        case 19:
            /* Matches "                   ." */
            if (c != '.') {
                expected = "'.'";
            }
            break;

        default:
            /* Matches "YYYY MM DD hh mm ss uuuuuu" */
            if(c < '0' || c > '9') {
                expected = "a digit";
            }
            break;
        }

        if(expected != NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid character in timestamp at position %i."
                          " Expected %s, got '%c'. Full timestamp: \"%s\"",
                          i, expected, c, timestamp);
            return 0;
        }
    }

    if (timestamp[len - 1] != 'Z') {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Timestamp wasn't in UTC (did not end with 'Z')."
                      " Full timestamp: \"%s\"",
                      timestamp);
        return 0;
    }


    time_exp.tm_usec = 0;
    if (len > 20) {
        /* Subsecond precision. */
        if (len > 27) {
            /* Timestamp has more than microsecond precision. Just clip it to
             * microseconds.
             */
            len = 27;
        }
        len -= 1; /* Drop the 'Z' off the end. */
        for (i = 20; i < len; i++) {
            time_exp.tm_usec = time_exp.tm_usec * 10 + timestamp[i] - '0';
        }
        for (i = len; i < 26; i++) {
            time_exp.tm_usec *= 10;
        }
    }

    time_exp.tm_sec = (timestamp[17] - '0') * 10 + (timestamp[18] - '0');
    time_exp.tm_min = (timestamp[14] - '0') * 10 + (timestamp[15] - '0');
    time_exp.tm_hour = (timestamp[11] - '0') * 10 + (timestamp[12] - '0');
    time_exp.tm_mday = (timestamp[8] - '0') * 10 + (timestamp[9] - '0');
    time_exp.tm_mon = (timestamp[5] - '0') * 10 + (timestamp[6] - '0') - 1;
    time_exp.tm_year = (timestamp[0] - '0') * 1000 +
        (timestamp[1] - '0') * 100 + (timestamp[2] - '0') * 10 +
        (timestamp[3] - '0') - 1900;

    time_exp.tm_wday = 0; /* Unknown. */
    time_exp.tm_yday = 0; /* Unknown. */

    time_exp.tm_isdst = 0; /* UTC, no daylight savings time. */
    time_exp.tm_gmtoff = 0; /* UTC, no offset from UTC. */

    rc = apr_time_exp_gmt_get(&res, &time_exp);
    if(rc != APR_SUCCESS) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                      "Error converting timestamp \"%s\".",
                      timestamp);
        return 0;
    }

    return res;
}


/* Validate the subject on an Assertion.
 *
 *  request_rec *r                   The current request. Used to log
 *                                   errors.
 *  LassoSaml2Assertion *assertion   The assertion we will validate.
 *  const char *url                  The current URL.
 *
 * Returns:
 *  OK on success, HTTP_BAD_REQUEST on failure.
 */
static int am_validate_subject(request_rec *r, LassoSaml2Assertion *assertion,
                               const char *url)
{
    apr_time_t now;
    apr_time_t t;
    LassoSaml2SubjectConfirmation *sc;
    LassoSaml2SubjectConfirmationData *scd;
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);

    if (assertion->Subject == NULL) {
        /* No Subject to validate. */
        return OK;
    } else if (!LASSO_IS_SAML2_SUBJECT(assertion->Subject)) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Wrong type of Subject node.");
        return HTTP_BAD_REQUEST;
    }

    if (assertion->Subject->SubjectConfirmation == NULL) {
        /* No SubjectConfirmation. */
        return OK;
    } else if (!LASSO_IS_SAML2_SUBJECT_CONFIRMATION(assertion->Subject->SubjectConfirmation)) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Wrong type of SubjectConfirmation node.");
        return HTTP_BAD_REQUEST;
    }

    sc = assertion->Subject->SubjectConfirmation;
    if (sc->Method == NULL ||
        strcmp(sc->Method, "urn:oasis:names:tc:SAML:2.0:cm:bearer")) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Invalid Method in SubjectConfirmation.");
        return HTTP_BAD_REQUEST;
    }

    scd = sc->SubjectConfirmationData;
    if (scd == NULL) {
        /* Nothing to verify. */
        return OK;
    } else if (!LASSO_IS_SAML2_SUBJECT_CONFIRMATION_DATA(scd)) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Wrong type of SubjectConfirmationData node.");
        return HTTP_BAD_REQUEST;
    }

    now = apr_time_now();

    if (scd->NotBefore) {
        t = am_parse_timestamp(r, scd->NotBefore);
        if (t == 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid timestamp in NotBefore in SubjectConfirmationData.");
            return HTTP_BAD_REQUEST;
        }
        if (t - 60000000 > now) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "NotBefore in SubjectConfirmationData was in the future.");
            return HTTP_BAD_REQUEST;
        }
    }

    if (scd->NotOnOrAfter) {
        t = am_parse_timestamp(r, scd->NotOnOrAfter);
        if (t == 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid timestamp in NotOnOrAfter in SubjectConfirmationData.");
            return HTTP_BAD_REQUEST;
        }
        if (now >= t + 60000000) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "NotOnOrAfter in SubjectConfirmationData was in the past.");
            return HTTP_BAD_REQUEST;
        }
    }

    if (scd->Recipient) {
        if (strcmp(scd->Recipient, url)) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Wrong Recipient in SubjectConfirmationData. Current URL is: %s, Recipient is %s",
                          url, scd->Recipient);
            return HTTP_BAD_REQUEST;
        }
    }

    if (scd->Address && CFG_VALUE(cfg, subject_confirmation_data_address_check)) {
        if (strcasecmp(scd->Address, am_compat_request_ip(r))) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Wrong Address in SubjectConfirmationData."
                          "Current address is \"%s\", but should have been \"%s\".",
                          am_compat_request_ip(r), scd->Address);
            return HTTP_BAD_REQUEST;
        }
    }

    return OK;
}


/* Validate the conditions on an Assertion.
 *
 * Parameters:
 *  request_rec *r                   The current request. Used to log
 *                                   errors.
 *  LassoSaml2Assertion *assertion   The assertion we will validate.
 *  const char *providerID           The providerID of the SP.
 *
 * Returns:
 *  OK on success, HTTP_BAD_REQUEST on failure.
 */
static int am_validate_conditions(request_rec *r,
                                  LassoSaml2Assertion *assertion,
                                  const char *providerID)
{
    LassoSaml2Conditions *conditions;
    apr_time_t now;
    apr_time_t t;
    GList *i;
    LassoSaml2AudienceRestriction *ar;

    conditions = assertion->Conditions;
    if (!LASSO_IS_SAML2_CONDITIONS(conditions)) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Wrong type of Conditions node.");
        return HTTP_BAD_REQUEST;
    }

    if (conditions->Condition != NULL) {
        /* This is a list of LassoSaml2ConditionAbstract - if it
         * isn't empty, we have an unsupported condition.
         */
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Unsupported condition in Assertion.");
        return HTTP_BAD_REQUEST;
    }


    now = apr_time_now();

    if (conditions->NotBefore) {
        t = am_parse_timestamp(r, conditions->NotBefore);
        if (t == 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid timestamp in NotBefore in Condition.");
            return HTTP_BAD_REQUEST;
        }
        if (t - 60000000 > now) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "NotBefore in Condition was in the future.");
            return HTTP_BAD_REQUEST;
        }
    }

    if (conditions->NotOnOrAfter) {
        t = am_parse_timestamp(r, conditions->NotOnOrAfter);
        if (t == 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid timestamp in NotOnOrAfter in Condition.");
            return HTTP_BAD_REQUEST;
        }
        if (now >= t + 60000000) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "NotOnOrAfter in Condition was in the past.");
            return HTTP_BAD_REQUEST;
        }
    }

    for (i = g_list_first(conditions->AudienceRestriction); i != NULL;
         i = g_list_next(i)) {
        ar = i->data;
        if (!LASSO_IS_SAML2_AUDIENCE_RESTRICTION(ar)) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Wrong type of AudienceRestriction node.");
            return HTTP_BAD_REQUEST;
        }

        if (ar->Audience == NULL || strcmp(ar->Audience, providerID)) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid Audience in Conditions. Should be: %s",
                          providerID);
            return HTTP_BAD_REQUEST;
        }
    }

    return OK;
}



/* This function sets the session expire timestamp based on NotOnOrAfter
 * attribute of a condition element.
 *
 * Parameters:
 *  request_rec *r                   The current request. Used to log
 *                                   errors.
 *  am_cache_entry_t *session        The current session.
 *  LassoSaml2Assertion *assertion   The assertion which we will extract
 *                                   the conditions from.
 *
 * Returns:
 *  Nothing.
 */
static void am_handle_session_expire(request_rec *r, am_cache_entry_t *session,
                                LassoSaml2Assertion *assertion)
{
    GList *authn_itr;
    LassoSaml2AuthnStatement *authn;
    const char *not_on_or_after;
    apr_time_t t;

    for(authn_itr = g_list_first(assertion->AuthnStatement); authn_itr != NULL;
        authn_itr = g_list_next(authn_itr)) {

        authn = authn_itr->data;
        if (!LASSO_IS_SAML2_AUTHN_STATEMENT(authn)) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Wrong type of AuthnStatement node.");
            continue;
        }

        /* Find timestamp. */
        not_on_or_after = authn->SessionNotOnOrAfter;
        if(not_on_or_after == NULL) {
            continue;
        }


        /* Parse timestamp. */
        t = am_parse_timestamp(r, not_on_or_after);
        if(t == 0) {
            continue;
        }

        /* Updates the expires timestamp if this one is earlier than the
         * previous timestamp.
         */
        am_cache_update_expires(session, t);
    }
}


/* This function is for decoding and storing attributes with the feide
 * encoding. It takes in an attribute name and a value. The value is split
 * into multiple values. We base64 decode these values, and store them in the
 * session data.
 *
 * Parameters:
 *  request_rec *r              The current request.
 *  am_cache_entry_t *session   The current session.
 *  const char *name            Name of the attribute.
 *  const char *value           The value(s) of the attribute.
 *
 * Returns:
 *  OK on success or an error from am_cache_env_append(...) if it was unable
 *  to store the attribute.
 */
static int am_store_attribute_feide(request_rec *r, am_cache_entry_t *session,
                                    const char *name, const char *value)
{
    char *edit_value;
    char *start; 
    char *next;
    int len;
    int ret;

    /* We need to be able to change the value. */
    edit_value = apr_pstrdup(r->pool, value);

    for(start = edit_value; start != NULL; start = next) {
        /* The values are separated by '_'. */
        next = strchr(start, '_');

        if(next != NULL) {
            /* Insert null-terminator after current value. */
            *next = '\0';

            /* The next value begins at next+1. */
            next++;
        }

        /* Now start points to the current value, which we have
         * null-terminated. next points to the next value, or NULL if
         * this is the last value.
         */

        /* base64-decode current value.
         * From looking at the source of apr_base64_decode_binary, it
         * appears to be safe to use in-place.
         */
        len = apr_base64_decode_binary((unsigned char *)start, start);

        /* Add null-terminator at end of string. */
        start[len] = '\0';


        /* Store current name-value-pair. */
        ret = am_cache_env_append(session, name, start);
        if(ret != OK) {
            return ret;
        }
    }

    return OK;
}


/* This function is for storing attributes without any encoding. We just store
 * the attribute as it is.
 *
 * Parameters:
 *  request_rec *r              The current request.
 *  am_cache_entry_t *session   The current session.
 *  const char *name            The name of the attribute.
 *  const char *value           The value of the attribute.
 *
 * Returns:
 *  OK on success or an error from am_cache_env_append(...) if it failed.
 */
static int am_store_attribute_none(request_rec *r, am_cache_entry_t *session,
                                   const char *name, const char *value)
{
    /* Store current name-value-pair. */
    return am_cache_env_append(session, name, value);
}


/* This function passes a name-value pair to the decoder selected by the
 * MellonDecoder configuration option. The decoder will decode the value
 * and store it in the session data.
 *
 * Parameters:
 *  request_rec *r              The current request.
 *  am_cache_entry_t *session   The current session.
 *  const char *name            The name of the attribute.
 *  const char *value           The value of the attribute.
 *
 * Returns:
 *  OK on success or an error from the attribute decoder if it failed.
 */
static int am_store_attribute(request_rec *r, am_cache_entry_t *session,
                              const char *name, const char *value)
{
    am_dir_cfg_rec *dir_cfg;

    dir_cfg = am_get_dir_cfg(r);

    switch(dir_cfg->decoder) {
    case am_decoder_none:
        return am_store_attribute_none(r, session, name, value);

    case am_decoder_feide:
        return am_store_attribute_feide(r, session, name, value);

    default:
        return am_store_attribute_none(r, session, name, value);
    }
}


/* Add all the attributes from an assertion to the session data for the
 * current user.
 *
 * Parameters:
 *  am_cache_entry_t *s             The current session.
 *  request_rec *r                  The current request.
 *  const char *name_id             The name identifier we received from
 *                                  the IdP.
 *  LassoSaml2Assertion *assertion  The assertion.
 *
 * Returns:
 *  HTTP_BAD_REQUEST if we couldn't find the session id of the user, or
 *  OK if no error occured.
 */
static int add_attributes(am_cache_entry_t *session, request_rec *r,
                          const char *name_id, LassoSaml2Assertion *assertion)
{
    am_dir_cfg_rec *dir_cfg;
    GList *atr_stmt_itr;
    LassoSaml2AttributeStatement *atr_stmt;
    GList *atr_itr;
    LassoSaml2Attribute *attribute;
    GList *value_itr;
    LassoSaml2AttributeValue *value;
    LassoMiscTextNode *value_text;
    int ret;

    dir_cfg = am_get_dir_cfg(r);

    /* Set expires to whatever is set by MellonSessionLength. */
    if(dir_cfg->session_length == -1) {
        /* -1 means "use default. The current default is 86400 seconds. */
        am_cache_update_expires(session, apr_time_now()
                                + apr_time_make(86400, 0));
    } else {
        am_cache_update_expires(session, apr_time_now()
                                + apr_time_make(dir_cfg->session_length, 0));
    }

    /* Save session information. */
    ret = am_cache_env_append(session, "NAME_ID", name_id);
    if(ret != OK) {
        return ret;
    }

    /* Update expires timestamp of session. */
    am_handle_session_expire(r, session, assertion);

    /* assertion->AttributeStatement is a list of
     * LassoSaml2AttributeStatement objects.
     */
    for(atr_stmt_itr = g_list_first(assertion->AttributeStatement);
        atr_stmt_itr != NULL;
        atr_stmt_itr = g_list_next(atr_stmt_itr)) {

        atr_stmt = atr_stmt_itr->data;
        if (!LASSO_IS_SAML2_ATTRIBUTE_STATEMENT(atr_stmt)) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Wrong type of AttributeStatement node.");
            continue;
        }

        /* atr_stmt->Attribute is list of LassoSaml2Attribute objects. */
        for(atr_itr = g_list_first(atr_stmt->Attribute);
            atr_itr != NULL;
            atr_itr = g_list_next(atr_itr)) {

            attribute = atr_itr->data;
            if (!LASSO_IS_SAML2_ATTRIBUTE(attribute)) {
                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                              "Wrong type of Attribute node.");
                continue;
            }

            /* attribute->AttributeValue is a list of
             * LassoSaml2AttributeValue objects.
             */
            for(value_itr = g_list_first(attribute->AttributeValue);
                value_itr != NULL;
                value_itr = g_list_next(value_itr)) {

                value = value_itr->data;
                if (!LASSO_IS_SAML2_ATTRIBUTE_VALUE(value)) {
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                                  "Wrong type of AttributeValue node.");
                    continue;
                }

                /* value->any is a list with the child nodes of the
                 * AttributeValue element.
                 *
                 * We assume that the list contains a single text node.
                 */
                if(value->any == NULL) {
                    ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                                  "AttributeValue element was empty.");
                    continue;
                }

                /* Verify that this is a LassoMiscTextNode object. */
                if(!LASSO_IS_MISC_TEXT_NODE(value->any->data)) {
                    ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                                  "AttributeValue element contained an "
                                  " element which wasn't a text node.");
                    continue;
                }

                value_text = LASSO_MISC_TEXT_NODE(value->any->data);


                /* Decode and save the attribute. */
                ret = am_store_attribute(r, session, attribute->Name,
                                         value_text->content);
                if(ret != OK) {
                    return ret;
                }
            }
        }
    }

    return OK;
}

/* This function validates that the received assertion verify the security level configured by
 * MellonAuthnContextClassRef directives
 */
static int am_validate_authn_context_class_ref(request_rec *r,
        LassoSaml2Assertion *assertion) {
    int i = 0;
    LassoSaml2AuthnStatement *authn_statement = NULL;
    LassoSaml2AuthnContext *authn_context = NULL;
    am_dir_cfg_rec *dir_cfg;
    apr_array_header_t *refs;

    dir_cfg = am_get_dir_cfg(r);
    refs = dir_cfg->authn_context_class_ref;
    if (! refs->nelts)
        return OK;

    if (! assertion->AuthnStatement) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Missing AuthnStatement in assertion, returning BadRequest.");
        return HTTP_BAD_REQUEST;
    }
    /* we only consider the first AuthnStatement, I do not know of any idp
     * sending more than one. */
    authn_statement = g_list_first(assertion->AuthnStatement)->data;
    if (! authn_statement->AuthnContext) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Missing AuthnContext in assertion, returning BadRequest.");
        return HTTP_BAD_REQUEST;
    }
    authn_context = authn_statement->AuthnContext;
    if (! authn_context->AuthnContextClassRef) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Missing AuthnContextClassRef in assertion, returning Forbidden.");
        return HTTP_FORBIDDEN;
    }
    for (i = 0; i < refs->nelts; i++) {
        const char *ref = ((char **)refs->elts)[i];
        if (strcmp(ref, authn_context->AuthnContextClassRef) == 0) {
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                          "AuthnContextClassRef (%s) matches the "
                          "MellonAuthnContextClassRef directive, "
                          "access can be granted.",
                          authn_context->AuthnContextClassRef);
            return OK;
        }
    }
    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                  "AuthnContextClassRef (%s) does not match the "
                  "MellonAuthnContextClassRef directive, returning "
                  "Forbidden.",
                  authn_context->AuthnContextClassRef);
    return HTTP_FORBIDDEN;
}

/* This function finishes handling of a login response after it has been parsed
 * by the HTTP-POST or HTTP-Artifact handler.
 *
 * Parameters:
 *  request_rec *r       The current request.
 *  LassoLogin *login    The login object which has been initialized with the
 *                       data we have received from the IdP.
 *  char *relay_state    The RelayState parameter from the POST data or from
 *                       the request url. This parameter is urlencoded, and
 *                       this function will urldecode it in-place. Therefore it
 *                       must be possible to overwrite the data.
 *
 * Returns:
 *  A HTTP status code which should be returned to the client.
 */
static int am_handle_reply_common(request_rec *r, LassoLogin *login,
                                  char *relay_state, char *saml_response)
{
    char *url;
    char *chr;
    const char *name_id;
    LassoSamlp2Response *response;
    LassoSaml2Assertion *assertion;
    const char *in_response_to;
    am_dir_cfg_rec *dir_cfg;
    am_cache_entry_t *session;
    int rc;
    const char *idp;

    url = am_reconstruct_url(r);
    chr = strchr(url, '?');
    if (! chr) {
        chr = strchr(url, ';');
    }
    if (chr) {
        *chr = '\0';
    }


    dir_cfg = am_get_dir_cfg(r);

    if(LASSO_PROFILE(login)->nameIdentifier == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "No acceptable name identifier found in"
                      " SAML 2.0 response.");
        lasso_login_destroy(login);
        return HTTP_BAD_REQUEST;
    }

    name_id = LASSO_SAML2_NAME_ID(LASSO_PROFILE(login)->nameIdentifier)
        ->content;

    response = LASSO_SAMLP2_RESPONSE(LASSO_PROFILE(login)->response);

    if (response->parent.Destination) {
        if (strcmp(response->parent.Destination, url)) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid Destination on Response. Should be: %s",
                          url);
            lasso_login_destroy(login);
            return HTTP_BAD_REQUEST;
        }
    }

    if (g_list_length(response->Assertion) == 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "No Assertion in response.");
        lasso_login_destroy(login);
        return HTTP_BAD_REQUEST;
    }
    if (g_list_length(response->Assertion) > 1) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "More than one Assertion in response.");
        lasso_login_destroy(login);
        return HTTP_BAD_REQUEST;
    }
    assertion = g_list_first(response->Assertion)->data;
    if (!LASSO_IS_SAML2_ASSERTION(assertion)) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Wrong type of Assertion node.");
        lasso_login_destroy(login);
        return HTTP_BAD_REQUEST;
    }

    rc = am_validate_subject(r, assertion, url);
    if (rc != OK) {
        lasso_login_destroy(login);
        return rc;
    }

    rc = am_validate_conditions(r, assertion,
        LASSO_PROVIDER(LASSO_PROFILE(login)->server)->ProviderID);

    if (rc != OK) {
        lasso_login_destroy(login);
        return rc;
    }

    in_response_to = response->parent.InResponseTo;


    if(in_response_to != NULL) {
        /* This is SP-initiated login. Check that we have a cookie. */
        if(am_cookie_get(r) == NULL) {
            /* Missing cookie. */
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                          "User has disabled cookies, or has lost"
                          " the cookie before returning from the SAML2"
                          " login server.");
            if(dir_cfg->no_cookie_error_page != NULL) {
                apr_table_setn(r->headers_out, "Location",
                               dir_cfg->no_cookie_error_page);
                lasso_login_destroy(login);
                return HTTP_SEE_OTHER;
            } else {
                /* Return 400 Bad Request when the user hasn't set a
                 * no-cookie error page.
                 */
                lasso_login_destroy(login);
                return HTTP_BAD_REQUEST;
            }
        }
    }

    /* Check AuthnContextClassRef */
    rc = am_validate_authn_context_class_ref(r, assertion);
    if (rc != OK) {
        lasso_login_destroy(login);
        return rc;
    }

    /* Create a new session. */
    session = am_new_request_session(r);
    if(session == NULL) {
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
                    "am_new_request_session() failed");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    rc = add_attributes(session, r, name_id, assertion);
    if(rc != OK) {
        am_release_request_session(r, session);
        lasso_login_destroy(login);
        return rc;
    }

    /* If requested, save the IdP ProviderId */
    if(dir_cfg->idpattr != NULL) {
        idp = LASSO_PROFILE(login)->remote_providerID;
        if(idp != NULL) {
            rc = am_cache_env_append(session, dir_cfg->idpattr, idp);
            if(rc != OK) {
                am_release_request_session(r, session);
                lasso_login_destroy(login);
                return rc;
            }
        }
    }

    rc = lasso_login_accept_sso(login);
    if(rc < 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Unable to accept SSO message."
                      " Lasso error: [%i] %s", rc, lasso_strerror(rc));
        am_release_request_session(r, session);
        lasso_login_destroy(login);
        return HTTP_INTERNAL_SERVER_ERROR;
    }


    /* Save the profile state. */
    rc = am_save_lasso_profile_state(r, session, LASSO_PROFILE(login),
                                     saml_response);
    if(rc != OK) {
        am_release_request_session(r, session);
        lasso_login_destroy(login);
        return rc;
    }

    /* Mark user as logged in. */
    session->logged_in = 1;

    am_release_request_session(r, session);
    lasso_login_destroy(login);


    /* No RelayState - we don't know what to do. Use default login path. */
    if(relay_state == NULL || strlen(relay_state) == 0) {
       dir_cfg = am_get_dir_cfg(r);
       apr_table_setn(r->headers_out, "Location", dir_cfg->login_path);
       return HTTP_SEE_OTHER;
    }

    rc = am_urldecode(relay_state);
    if (rc != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                      "Could not urldecode RelayState value.");
        return HTTP_BAD_REQUEST;
    }

    /* Check for bad characters in RelayState. */
    rc = am_check_url(r, relay_state);
    if (rc != OK) {
        return rc;
    }

    apr_table_setn(r->headers_out, "Location",
                   relay_state);

    /* HTTP_SEE_OTHER should be a redirect where the browser doesn't repeat
     * the POST data to the new page.
     */
    return HTTP_SEE_OTHER;
}


/* This function handles responses to login requests received with the
 * HTTP-POST binding.
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  HTTP_SEE_OTHER on success, or an error on failure.
 */
static int am_handle_post_reply(request_rec *r)
{
    int rc;
    char *post_data;
    char *saml_response;
    LassoServer *server;
    LassoLogin *login;
    char *relay_state;
    am_dir_cfg_rec *dir_cfg = am_get_dir_cfg(r);
    int i, err;

    /* Make sure that this is a POST request. */
    if(r->method_number != M_POST) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Expected POST request for HTTP-POST endpoint."
                      " Got a %s request instead.", r->method);

        /* According to the documentation for request_rec, a handler which
         * doesn't handle a request method, should set r->allowed to the
         * methods it handles, and return DECLINED.
         * However, the default handler handles GET-requests, so for GET
         * requests the handler should return HTTP_METHOD_NOT_ALLOWED.
         */
        r->allowed = M_POST;

        if(r->method_number == M_GET) {
            return HTTP_METHOD_NOT_ALLOWED;
        } else {
            return DECLINED;
        }
    }

    /* Read POST-data. */
    rc = am_read_post_data(r, &post_data, NULL);
    if (rc != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                      "Error reading POST data.");
        return rc;
    }

    /* Extract the SAMLResponse-field from the data. */
    saml_response = am_extract_query_parameter(r->pool, post_data,
                                            "SAMLResponse");
    if (saml_response == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                      "Could not find SAMLResponse field in POST data.");
        return HTTP_BAD_REQUEST;
    }

    rc = am_urldecode(saml_response);
    if (rc != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                      "Could not urldecode SAMLResponse value.");
        return rc;
    }

    server = am_get_lasso_server(r);
    if(server == NULL) {
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    login = lasso_login_new(server);
    if (login == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Failed to initialize LassoLogin object.");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Process login responce. */
    rc = lasso_login_process_authn_response_msg(login, saml_response);
    if (rc != 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error processing authn response."
                      " Lasso error: [%i] %s", rc, lasso_strerror(rc));

        lasso_login_destroy(login);
        err = HTTP_BAD_REQUEST;
        for (i = 0; auth_mellon_errormap[i].lasso_error != 0; i++) {
            if (auth_mellon_errormap[i].lasso_error == rc) {
                err = auth_mellon_errormap[i].http_error;
                break;
            }
        }
        if (err == HTTP_UNAUTHORIZED) {
            if (dir_cfg->no_success_error_page != NULL) {
                apr_table_setn(r->headers_out, "Location",
                               dir_cfg->no_success_error_page);
                return HTTP_SEE_OTHER;
            }
        }
        return err;
    }

    /* Extract RelayState parameter. */
    relay_state = am_extract_query_parameter(r->pool, post_data,
                                               "RelayState");

    /* Finish handling the reply with the common handler. */
    return am_handle_reply_common(r, login, relay_state, saml_response);
}


/* This function handles responses to login requests which use the
 * HTTP-Artifact binding.
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  HTTP_SEE_OTHER on success, or an error on failure.
 */
static int am_handle_artifact_reply(request_rec *r)
{
    int rc;
    LassoServer *server;
    LassoLogin *login;
    char *response;
    char *relay_state;
    char *saml_art;
    char *post_data;

    /* Make sure that this is a GET request. */
    if(r->method_number != M_GET && r->method_number != M_POST) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Expected GET or POST request for the HTTP-Artifact endpoint."
                      " Got a %s request instead.", r->method);

        /* According to the documentation for request_rec, a handler which
         * doesn't handle a request method, should set r->allowed to the
         * methods it handles, and return DECLINED.
         * However, the default handler handles GET-requests, so for GET
         * requests the handler should return HTTP_METHOD_NOT_ALLOWED.
         * This endpoints handles GET requests, so it isn't necessary to
         * check for method_number == M_GET.
         */
        r->allowed = M_GET;

        return DECLINED;
    }

    server = am_get_lasso_server(r);
    if(server == NULL) {
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    login = lasso_login_new(server);
    if (login == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Failed to initialize LassoLogin object.");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Parse artifact url. */
    if (r->method_number == M_GET) {
        rc = lasso_login_init_request(login, r->args,
                                  LASSO_HTTP_METHOD_ARTIFACT_GET);

        if(rc < 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Failed to handle login response."
                          " Lasso error: [%i] %s", rc, lasso_strerror(rc));
            lasso_login_destroy(login);
            return HTTP_BAD_REQUEST;
        }
    } else {
        rc = am_read_post_data(r, &post_data, NULL);
        if (rc != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                    "Error reading POST data.");
            return HTTP_BAD_REQUEST;
        }

        saml_art = am_extract_query_parameter(r->pool, post_data, "SAMLart");
        if (saml_art == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
                    "Error reading POST data missing SAMLart form parameter.");
            return HTTP_BAD_REQUEST;
        }
        ap_unescape_url(saml_art);

        rc = lasso_login_init_request(login, saml_art, LASSO_HTTP_METHOD_ARTIFACT_POST);
        if(rc < 0) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Failed to handle login response."
                          " Lasso error: [%i] %s", rc, lasso_strerror(rc));
            lasso_login_destroy(login);
            return HTTP_BAD_REQUEST;
        }
    }

    /* Prepare SOAP request. */
    rc = lasso_login_build_request_msg(login);
    if(rc < 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Failed to prepare SOAP message for HTTP-Artifact"
                      " resolution."
                      " Lasso error: [%i] %s", rc, lasso_strerror(rc));
        lasso_login_destroy(login);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Do the SOAP request. */
    rc = am_httpclient_post_str(
        r,
        LASSO_PROFILE(login)->msg_url,
        LASSO_PROFILE(login)->msg_body,
        "text/xml",
        (void**)&response,
        NULL
        );
    if(rc != OK) {
        lasso_login_destroy(login);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    rc = lasso_login_process_response_msg(login, response);
    if(rc != 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Failed to handle HTTP-Artifact response data."
                      " Lasso error: [%i] %s", rc, lasso_strerror(rc));
        lasso_login_destroy(login);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Extract the RelayState parameter. */
    if (r->method_number == M_GET) {
        relay_state = am_extract_query_parameter(r->pool, r->args,
                                                   "RelayState");
    } else {
        relay_state = am_extract_query_parameter(r->pool, post_data,
                                                   "RelayState");
    }

    /* Finish handling the reply with the common handler. */
    return am_handle_reply_common(r, login, relay_state, "");
}



/* This function builds web form inputs for a saved POST request, 
 * in multipart/form-data format.
 *
 * Parameters:
 *  request_rec *r        The request
 *  const char *post_data The savec POST request
 *
 * Returns:
 *  The web form fragment, or NULL on failure.
 */
const char *am_post_mkform_multipart(request_rec *r, const char *post_data)
{
    const char *mime_part;
    const char *boundary;
    char *l1;
    char *post_form = "";

    /* Replace CRLF by LF */
    post_data = am_strip_cr(r, post_data);

    if ((boundary = am_xstrtok(r, post_data, "\n", &l1)) == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                     "Cannot figure initial boundary");
        return NULL;
    }

    for (mime_part = am_xstrtok(r, post_data, boundary, &l1); mime_part;
         mime_part = am_xstrtok(r, NULL, boundary, &l1)) {
        const char *hdr;
        const char *name = NULL;
        const char *value = NULL;
        const char *input_item;

        /* End of MIME data */
        if (strcmp(mime_part, "--\n") == 0)
            break;

        /* Remove leading CRLF */
        if (strstr(mime_part, "\n") == mime_part)
            mime_part += 1;

        /* Empty part */
        if (*mime_part == '\0')
            continue;

        /* Find Content-Disposition header 
         * Looking for 
         * Content-Disposition: form-data; name="the_name"\n 
         */
        hdr = am_get_mime_header(r, mime_part, "Content-Disposition");
        if (hdr == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                         "No Content-Disposition header in MIME section,");
            continue;
        }

        name = am_get_header_attr(r, hdr, "form-data", "name");
        if (name == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                         "Unexpected Content-Disposition header: \"%s\"", hdr);
            continue;
        }

        if ((value = am_get_mime_body(r, mime_part)) == NULL)
            value = "";

        input_item = apr_psprintf(r->pool, 
                    "    <input type=\"hidden\" name=\"%s\" value=\"%s\">\n",
                    am_htmlencode(r, name), am_htmlencode(r, value));
        post_form = apr_pstrcat(r->pool, post_form, input_item, NULL);
    }

    return post_form;
}

/* This function builds web form inputs for a saved POST request, 
 * in application/x-www-form-urlencoded format
 *
 * Parameters:
 *  request_rec *r        The request
 *  const char *post_data The savec POST request
 *
 * Returns:
 *  The web form fragment, or NULL on failure.
 */
const char *am_post_mkform_urlencoded(request_rec *r, const char *post_data)
{
    const char *item;
    char *last;
    char *post_form = "";

    for (item = am_xstrtok(r, post_data, "&", &last); item; 
         item = am_xstrtok(r, NULL, "&", &last)) {
        char *l1;
        char *name;
        char *value;
        const char *input_item;

        name = (char *)am_xstrtok(r, item, "=", &l1);  
        value = (char *)am_xstrtok(r, NULL, "=", &l1);

        if (name == NULL)
            continue;

        if (value == NULL)
            value = (char *)"";

        if (am_urldecode(name) != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                         "urldecode(\"%s\") failed", name);
            return NULL;
        }

        if (am_urldecode(value) != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                         "urldecode(\"%s\") failed", value);
            return NULL;
        }

        input_item = apr_psprintf(r->pool, 
                    "    <input type=\"hidden\" name=\"%s\" value=\"%s\">\n",
                    am_htmlencode(r, name), am_htmlencode(r, value));
        post_form = apr_pstrcat(r->pool, post_form, input_item, NULL);
    }
    return post_form;
}


/* This function handles responses to repost request
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  OK on success, or an error on failure.
 */
static int am_handle_repost(request_rec *r)
{
    am_mod_cfg_rec *mod_cfg;
    const char *query;
    const char *enctype;
    char *charset;
    char *psf_id;
    char *cp;
    char *psf_filename;
    char *post_data;
    const char *post_form;
    char *output;
    char *return_url;
    const char *(*post_mkform)(request_rec *, const char *);

    if (am_cookie_get(r) == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                      "Repost query without a session");
        return HTTP_FORBIDDEN;
    }

    mod_cfg = am_get_mod_cfg(r->server);

    if (!mod_cfg->post_dir) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Repost query without MellonPostDirectory.");
        return HTTP_NOT_FOUND;
    }

    query = r->parsed_uri.query;

    enctype = am_extract_query_parameter(r->pool, query, "enctype");
    if (enctype == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                      "Bad repost query: missing enctype");
        return HTTP_BAD_REQUEST;
    }
    if (strcmp(enctype, "urlencoded") == 0) {
        enctype = "application/x-www-form-urlencoded";
        post_mkform = am_post_mkform_urlencoded;
    } else if (strcmp(enctype, "multipart") == 0) {
        enctype = "multipart/form-data";
        post_mkform = am_post_mkform_multipart;
    } else {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                      "Bad repost query: invalid enctype \"%s\".", enctype);
        return HTTP_BAD_REQUEST;
    }

    charset = am_extract_query_parameter(r->pool, query, "charset");
    if (charset != NULL) {
        if (am_urldecode(charset) != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                          "Bad repost query: invalid charset \"%s\"", charset);
            return HTTP_BAD_REQUEST;
        }
    
        /* Check that charset is sane */
        for (cp = charset; *cp; cp++) {
            if (!apr_isalnum(*cp) && (*cp != '-') && (*cp != '_')) {
                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                              "Bad repost query: invalid charset \"%s\"", charset);
                return HTTP_BAD_REQUEST;
            }
        }
    }

    psf_id = am_extract_query_parameter(r->pool, query, "id");
    if (psf_id == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                      "Bad repost query: missing id");
        return HTTP_BAD_REQUEST;
    }

    /* Check that Id is sane */
    for (cp = psf_id; *cp; cp++) {
        if (!apr_isalnum(*cp)) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                          "Bad repost query: invalid id \"%s\"", psf_id);
            return HTTP_BAD_REQUEST;
        }
    }
    
    
    return_url = am_extract_query_parameter(r->pool, query, "ReturnTo");
    if (return_url == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Invalid or missing query ReturnTo parameter.");
        return HTTP_BAD_REQUEST;
    }

    if (am_urldecode(return_url) != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: return");
        return HTTP_BAD_REQUEST;
    }

    psf_filename = apr_psprintf(r->pool, "%s/%s", mod_cfg->post_dir, psf_id);
    post_data = am_getfile(r->pool, r->server, psf_filename);
    if (post_data == NULL) {
        /* Unable to load repost data. Just redirect us instead. */
        ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                      "Bad repost query: cannot find \"%s\"", psf_filename);
        apr_table_setn(r->headers_out, "Location", return_url);
        return HTTP_SEE_OTHER;
    }

    if ((post_form = (*post_mkform)(r, post_data)) == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "am_post_mkform() failed");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    if (charset != NULL) {
         ap_set_content_type(r, apr_psprintf(r->pool,
                             "text/html; charset=\"%s\"", charset));
         charset = apr_psprintf(r->pool, " accept-charset=\"%s\"", charset);
    } else {
         ap_set_content_type(r, "text/html");
         charset = (char *)"";
    }

    output = apr_psprintf(r->pool,
      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
      "<html>\n"
      " <head>\n" 
      "  <title>SAML rePOST request</title>\n" 
      " </head>\n" 
      " <body onload=\"document.getElementById('form').submit();\">\n" 
      "  <noscript>\n"
      "   Your browser does not support Javascript, \n"
      "   you must click the button below to proceed.\n"
      "  </noscript>\n"
      "   <form id=\"form\" method=\"POST\" action=\"%s\" enctype=\"%s\"%s>\n%s"
      "    <noscript>\n"
      "     <input type=\"submit\">\n"
      "    </noscript>\n"
      "   </form>\n"
      " </body>\n" 
      "</html>\n",
      am_htmlencode(r, return_url), enctype, charset, post_form);

    ap_rputs(output, r);
    return OK;
}


/* This function handles responses to metadata request
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  OK on success, or an error on failure.
 */
static int am_handle_metadata(request_rec *r)
{
#ifdef HAVE_lasso_server_new_from_buffers
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    LassoServer *server;
    const char *data;

    server = am_get_lasso_server(r);
    if(server == NULL)
        return HTTP_INTERNAL_SERVER_ERROR;

    cfg = cfg->inherit_server_from;

    data = cfg->sp_metadata_file;
    if (data == NULL)
        return HTTP_INTERNAL_SERVER_ERROR;

    ap_set_content_type(r, "application/samlmetadata+xml");

    ap_rputs(data, r);

    return OK;
#else  /* ! HAVE_lasso_server_new_from_buffers */

    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                  "metadata publishing require lasso 2.2.2 or higher");
    return HTTP_NOT_FOUND;
#endif
}


/* Send AuthnRequest using HTTP-Redirect binding.
 *
 * Note that this method frees the LassoLogin object.
 *
 * Parameters:
 *  request_rec *r
 *  LassoLogin *login
 *
 * Returns:
 *  HTTP_SEE_OTHER on success, or an error on failure.
 */
static int am_send_authn_request_redirect(request_rec *r, LassoLogin *login)
{
    char *redirect_to;

    /* The URL we should send the message to. */
    redirect_to = apr_pstrdup(r->pool, LASSO_PROFILE(login)->msg_url);

    /* Check if the lasso library added the RelayState. If lasso didn't add
     * a RelayState parameter, then we add one ourself. This should hopefully
     * be removed in the future.
     */
    if(strstr(redirect_to, "&RelayState=") == NULL
       && strstr(redirect_to, "?RelayState=") == NULL) {
        /* The url didn't contain the relaystate parameter. */
        redirect_to = apr_pstrcat(
            r->pool, redirect_to, "&RelayState=",
            am_urlencode(r->pool, LASSO_PROFILE(login)->msg_relayState),
            NULL
            );
    }
    apr_table_setn(r->headers_out, "Location", redirect_to);

    lasso_login_destroy(login);

    /* We don't want to include POST data (in case this was a POST request). */
    return HTTP_SEE_OTHER;
}

/* Send AuthnRequest using HTTP-POST binding.
 *
 * Note that this method frees the LassoLogin object.
 *
 * Parameters:
 *  request_rec *r         The request we are processing.
 *  LassoLogin *login      The login message.
 *
 * Returns:
 *  OK on success, or an error on failure.
 */
static int am_send_authn_request_post(request_rec *r, LassoLogin *login)
{
    char *url;
    char *message;
    char *relay_state;
    char *output;

    url = am_htmlencode(r, LASSO_PROFILE(login)->msg_url);
    message = am_htmlencode(r, LASSO_PROFILE(login)->msg_body);
    relay_state = am_htmlencode(r, LASSO_PROFILE(login)->msg_relayState);

    lasso_login_destroy(login);

    output = apr_psprintf(r->pool,
      "<!DOCTYPE html>\n"
      "<html>\n"
      " <head>\n"
      "  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
      "  <title>POST data</title>\n"
      " </head>\n"
      " <body onload=\"document.forms[0].submit()\">\n"
      "  <noscript><p>\n"
      "   <strong>Note:</strong> Since your browser does not support JavaScript, you must press the button below once to proceed.\n"
      "  </p></noscript>\n"
      "  <form method=\"POST\" action=\"%s\">\n"
      "    <input type=\"hidden\" name=\"SAMLRequest\" value=\"%s\">\n"
      "    <input type=\"hidden\" name=\"RelayState\" value=\"%s\">\n"
      "    <noscript>\n"
      "     <input type=\"submit\">\n"
      "    </noscript>\n"
      "  </form>\n"
      " </body>\n"
      "</html>\n",
      url, message, relay_state);

    ap_set_content_type(r, "text/html");
    ap_rputs(output, r);

    return OK;
}

/* Create and send an authentication request.
 *
 * Parameters:
 *  request_rec *r         The request we are processing.
 *  const char *idp        The entityID of the IdP.
 *  const char *return_to  The URL we should redirect to when receiving the request.
 *  int is_passive         Whether to send a passive request.
 *
 * Returns:
 *  HTTP response code indicating success or failure.
 */
static int am_send_authn_request(request_rec *r, const char *idp,
                           const char *return_to, int is_passive)
{
    LassoServer *server;
    LassoProvider *provider;
    LassoLogin *login;
    LassoSamlp2AuthnRequest *request;
    LassoHttpMethod http_method;
    char *sso_url;
    gint ret;
    am_dir_cfg_rec *dir_cfg;

    dir_cfg = am_get_dir_cfg(r);

    /* Add cookie for cookie test. We know that we should have
     * a valid cookie when we return from the IdP after SP-initiated
     * login.
     */
    am_cookie_set(r, "cookietest");


    server = am_get_lasso_server(r);
    if(server == NULL) {
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Find our IdP. */
    provider = lasso_server_get_provider(server, idp);
    if (provider == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Could not find metadata for the IdP \"%s\".",
                      idp);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Determine what binding and endpoint we should use when
     * sending the request.
     */
    http_method = LASSO_HTTP_METHOD_REDIRECT;
    sso_url = lasso_provider_get_metadata_one(
        provider, "SingleSignOnService HTTP-Redirect");
    if (sso_url == NULL) {
        /* HTTP-Redirect unsupported - try HTTP-POST. */
        http_method = LASSO_HTTP_METHOD_POST;
        sso_url = lasso_provider_get_metadata_one(
            provider, "SingleSignOnService HTTP-POST");
    }
    if (sso_url == NULL) {
        /* Both HTTP-Redirect and HTTP-POST unsupported - give up. */
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Could not find a supported SingleSignOnService endpoint"
                      " for the IdP \"%s\".", idp);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    login = lasso_login_new(server);
    if(login == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
		      "Error creating LassoLogin object from LassoServer.");
        g_free(sso_url);
	return HTTP_INTERNAL_SERVER_ERROR;
    }

    ret = lasso_login_init_authn_request(login, idp, http_method);
    if(ret != 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error creating login request."
                      " Lasso error: [%i] %s", ret, lasso_strerror(ret));
        g_free(sso_url);
	lasso_login_destroy(login);
	return HTTP_INTERNAL_SERVER_ERROR;
    }

    request = LASSO_SAMLP2_AUTHN_REQUEST(LASSO_PROFILE(login)->request);
    if(request->NameIDPolicy == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error creating login request. Please verify the "
                      "MellonSPMetadataFile directive.");
        g_free(sso_url);
        lasso_login_destroy(login);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    request->ForceAuthn = FALSE;
    request->IsPassive = is_passive;

    request->NameIDPolicy->AllowCreate = TRUE;

    LASSO_SAMLP2_REQUEST_ABSTRACT(request)->Consent
      = g_strdup(LASSO_SAML2_CONSENT_IMPLICIT);

    /* Add AuthnContextClassRef */
    if (dir_cfg->authn_context_class_ref->nelts) {
        apr_array_header_t *refs = dir_cfg->authn_context_class_ref;
        int i = 0;
        LassoSamlp2RequestedAuthnContext *req_authn_context;

        req_authn_context = (LassoSamlp2RequestedAuthnContext*)
            lasso_samlp2_requested_authn_context_new();

        request->RequestedAuthnContext = req_authn_context;

        for (i = 0; i < refs->nelts; i++) {
            const char *ref = ((char **)refs->elts)[i];
            req_authn_context->AuthnContextClassRef =
                    g_list_append(req_authn_context->AuthnContextClassRef,
                                    g_strdup(ref));
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                          "adding AuthnContextClassRef %s to the "
                          "AuthnRequest", ref);
        }
    }

    /*
     * Make sure the Destination attribute is set to the IdP
     * SingleSignOnService endpoint. This is required for
     * Shibboleth 2 interoperability, and older versions of
     * lasso (at least up to 2.2.91) did not do it.
     */
    if (LASSO_SAMLP2_REQUEST_ABSTRACT(request)->Destination == NULL) {
        LASSO_SAMLP2_REQUEST_ABSTRACT(request)->Destination = g_strdup(sso_url);
    }

    /* sso_url no longer needed. */
    g_free(sso_url);

    LASSO_PROFILE(login)->msg_relayState = g_strdup(return_to);

    ret = lasso_login_build_authn_request_msg(login);
    if(ret != 0) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error building login request."
                      " Lasso error: [%i] %s", ret, lasso_strerror(ret));
	lasso_login_destroy(login);
	return HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Time to actually send the authentication request. */
    switch (http_method) {
    case LASSO_HTTP_METHOD_REDIRECT:
        return am_send_authn_request_redirect(r, login);
    case LASSO_HTTP_METHOD_POST:
        return am_send_authn_request_post(r, login);
    default:
        /* We should never get here. */
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Unsupported http_method.");
        lasso_login_destroy(login);
        return HTTP_INTERNAL_SERVER_ERROR;
    }
}


/* Handle the "auth" endpoint.
 *
 * This endpoint is included for backwards-compatibility.
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  OK or HTTP_SEE_OTHER on success, an error on failure.
 */
static int am_handle_auth(request_rec *r)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    const char *relay_state;

    relay_state = am_reconstruct_url(r);

    /* Check if IdP discovery is in use and no IdP was selected yet */
    if ((cfg->discovery_url != NULL) &&
        (am_extract_query_parameter(r->pool, r->args, "IdP") == NULL)) {
        return am_start_disco(r, relay_state);
    }

    /* If IdP discovery is in use and we have an IdP selected,
     * set the relay_state
     */
    if (cfg->discovery_url != NULL) {
        char *return_url;

        return_url = am_extract_query_parameter(r->pool, r->args, "ReturnTo");
        if ((return_url != NULL) && am_urldecode((char *)return_url) == 0)
            relay_state = return_url;
    }

    return am_send_authn_request(r, am_get_idp(r), relay_state, FALSE);
}

/* This function handles requests to the login handler.
 *
 * Parameters:
 *  request_rec *r       The request.
 *
 * Returns:
 *  OK on success, or an error if any of the steps fail.
 */
static int am_handle_login(request_rec *r)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    char *idp_param;
    const char *idp;
    char *return_to;
    char *is_passive_str;
    int is_passive;
    int ret;

    return_to = am_extract_query_parameter(r->pool, r->args, "ReturnTo");
    if(return_to == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Missing required ReturnTo parameter.");
        return HTTP_BAD_REQUEST;
    }

    ret = am_urldecode(return_to);
    if(ret != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Error urldecoding ReturnTo parameter.");
        return ret;
    }

    idp_param = am_extract_query_parameter(r->pool, r->args, "IdP");
    if(idp_param != NULL) {
        ret = am_urldecode(idp_param);
        if(ret != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Error urldecoding IdP parameter.");
            return ret;
        }
    }

    is_passive_str = am_extract_query_parameter(r->pool, r->args, "IsPassive");
    if(is_passive_str != NULL) {
        ret = am_urldecode((char*)is_passive_str);
        if(ret != OK) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Error urldecoding IsPassive parameter.");
            return ret;
        }
        if(!strcmp(is_passive_str, "true")) {
            is_passive = TRUE;
        } else if(!strcmp(is_passive_str, "false")) {
            is_passive = FALSE;
        } else {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Invalid value for IsPassive parameter - must be \"true\" or \"false\".");
            return HTTP_BAD_REQUEST;
        }
    } else {
        is_passive = FALSE;
    }

    if(idp_param != NULL) {
        idp = idp_param;
    } else if(cfg->discovery_url) {
        if(is_passive) {
            /* We cannot currently do discovery with passive authentication requests. */
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                          "Discovery service with passive authentication request unsupported.");
            return HTTP_INTERNAL_SERVER_ERROR;
        }
        return am_start_disco(r, return_to);
    } else {
        /* No discovery service -- just use the default IdP. */
        idp = am_get_idp(r);
    }

    return am_send_authn_request(r, idp, return_to, is_passive);
}

/* This function probes an URL (HTTP GET)
 *
 * Parameters:
 *  request_rec *r       The request.
 *  const char *url      The URL
 *  int timeout          Timeout in seconds
 *
 * Returns:
 *  OK on success, or an error if any of the steps fail.
 */
static int am_probe_url(request_rec *r, const char *url, int timeout)
{
    void *dontcare;
    apr_size_t len;
    long status;
    int error;

    status = 0;
    if ((error = am_httpclient_get(r, url, &dontcare, &len, 
                                   timeout, &status)) != OK)
        return error;

    if (status != HTTP_OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Probe on \"%s\" returned HTTP %ld",
                      url, status);
        return status;
    }

    return OK;
}

/* This function handles requests to the probe discovery handler
 *
 * Parameters:
 *  request_rec *r       The request.
 *
 * Returns:
 *  OK on success, or an error if any of the steps fail.
 */
static int am_handle_probe_discovery(request_rec *r) {
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    LassoServer *server;
    const char *disco_idp = NULL;
    int timeout;
    char *return_to;
    char *idp_param;
    char *redirect_url;
    int ret;

    server = am_get_lasso_server(r);
    if(server == NULL) {
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /*
     * If built-in IdP discovery is not configured, return error.
     * For now we only have the get-metadata metadata method, so this
     * information is not saved in configuration nor it is checked here.
     */
    timeout = cfg->probe_discovery_timeout;
    if (timeout == -1) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "probe discovery handler invoked but not "
                      "configured. Plase set MellonProbeDiscoveryTimeout.");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    /*
     * Check for mandatory arguments early to avoid sending 
     * probles for nothing.
     */
    return_to = am_extract_query_parameter(r->pool, r->args, "return");
    if(return_to == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Missing required return parameter.");
        return HTTP_BAD_REQUEST;
    }

    ret = am_urldecode(return_to);
    if (ret != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, ret, r,
                      "Could not urldecode return value.");
        return HTTP_BAD_REQUEST;
    }

    idp_param = am_extract_query_parameter(r->pool, r->args, "returnIDParam");
    if(idp_param == NULL) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Missing required returnIDParam parameter.");
        return HTTP_BAD_REQUEST;
    }

    ret = am_urldecode(idp_param);
    if (ret != OK) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, ret, r,
                      "Could not urldecode returnIDParam value.");
        return HTTP_BAD_REQUEST;
    }

    /*
     * Proceed with built-in IdP discovery. 
     *
     * First try sending probes to IdP configured for discovery.
     * Second send probes for all configured IdP
     * The first to answer is chosen.
     * If none answer, use the first configured IdP
     */
    if (!apr_is_empty_table(cfg->probe_discovery_idp)) {
        const apr_array_header_t *header;
        apr_table_entry_t *elts;
        const char *url;
        const char *idp;
        int i;

        header = apr_table_elts(cfg->probe_discovery_idp);
        elts = (apr_table_entry_t *)header->elts;

        for (i = 0; i < header->nelts; i++) { 
            idp = elts[i].key;
            url = elts[i].val;

            if (am_probe_url(r, url, timeout) == OK) {
                disco_idp = idp;
                break;
            }
        }
    } else {
        GList *iter;
        GList *idp_list;
        const char *idp;

        idp_list = g_hash_table_get_keys(server->providers);
        for (iter = idp_list; iter != NULL; iter = iter->next) {
            idp = iter->data;
    
            if (am_probe_url(r, idp, timeout) == OK) {
                disco_idp = idp;
                break;
            }
        }
        g_list_free(idp_list);
    }

    /* 
     * On failure, try default
     */
    if (disco_idp == NULL) {
        disco_idp = am_first_idp(r);
        if (disco_idp == NULL) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 
                          "probeDiscovery found no usable IdP.");
            return HTTP_INTERNAL_SERVER_ERROR;
        } else {
            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "probeDiscovery "
                          "failed, trying default IdP %s", disco_idp); 
        }
    } else {
        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
                      "probeDiscovery using %s", disco_idp);
    }

    redirect_url = apr_psprintf(r->pool, "%s%s%s=%s", return_to, 
                                strchr(return_to, '?') ? "&" : "?",
                                am_urlencode(r->pool, idp_param), 
                                am_urlencode(r->pool, disco_idp));

    apr_table_setn(r->headers_out, "Location", redirect_url);

    return HTTP_SEE_OTHER;
}


/* This function handles responses to request on our endpoint
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  OK on success, or an error on failure.
 */
int am_handler(request_rec *r)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    const char *endpoint;

    /* Check if this is a request for one of our endpoints. We check if
     * the uri starts with the path set with the MellonEndpointPath
     * configuration directive.
     */
    if(strstr(r->uri, cfg->endpoint_path) != r->uri)
        return DECLINED;

    endpoint = &r->uri[strlen(cfg->endpoint_path)];
    if (!strcmp(endpoint, "metadata")) {
        return am_handle_metadata(r);
    } else if (!strcmp(endpoint, "repost")) {
        return am_handle_repost(r);
    } else if(!strcmp(endpoint, "postResponse")) {
        return am_handle_post_reply(r);
    } else if(!strcmp(endpoint, "artifactResponse")) {
        return am_handle_artifact_reply(r);
    } else if(!strcmp(endpoint, "auth")) {
        return am_handle_auth(r);
    } else if(!strcmp(endpoint, "logout")
              || !strcmp(endpoint, "logoutRequest")) {
        /* logoutRequest is included for backwards-compatibility
         * with version 0.0.6 and older.
         */
        return am_handle_logout(r);
    } else if(!strcmp(endpoint, "login")) {
        return am_handle_login(r);
    } else if(!strcmp(endpoint, "probeDisco")) {
        return am_handle_probe_discovery(r);
    } else {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Endpoint \"%s\" not handled by mod_auth_mellon.",
                      endpoint);

        return HTTP_NOT_FOUND;
    }
}


/**
 * Trigger a login operation from a "normal" request.
 *
 * Parameters:
 *  request_rec *r       The request we received.
 *
 * Returns:
 *  HTTP_SEE_OTHER on success, or an error on failure.
 */
static int am_start_auth(request_rec *r)
{
    am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
    const char *endpoint = am_get_endpoint_url(r);
    const char *return_to;
    const char *idp;
    const char *login_url;

    return_to = am_reconstruct_url(r);

    /* If this is a POST request, attempt to save it */
    if (r->method_number == M_POST) {
        if (CFG_VALUE(cfg, post_replay)) {
            if (am_save_post(r, &return_to) != OK)
                return HTTP_INTERNAL_SERVER_ERROR;
        } else {
            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                          "POST data dropped because we do not have a"
                          " MellonPostReplay is not enabled.");
        }
    }

    /* Check if IdP discovery is in use. */
    if (cfg->discovery_url) {
        return am_start_disco(r, return_to);
    }

    idp = am_get_idp(r);
    login_url = apr_psprintf(r->pool, "%slogin?ReturnTo=%s&IdP=%s",
                             endpoint,
                             am_urlencode(r->pool, return_to),
                             am_urlencode(r->pool, idp));
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                  "Redirecting to login URL: %s", login_url);

    apr_table_setn(r->headers_out, "Location", login_url);
    return HTTP_SEE_OTHER;
}

int am_auth_mellon_user(request_rec *r)
{
    am_dir_cfg_rec *dir = am_get_dir_cfg(r);
    int return_code = HTTP_UNAUTHORIZED;
    am_cache_entry_t *session;

    /* check if we are a subrequest.  if we are, then just return OK
     * without any checking since these cannot be injected (heh). */
    if (r->main)
        return OK;

    /* Check that the user has enabled authentication for this directory. */
    if(dir->enable_mellon == am_enable_off
       || dir->enable_mellon == am_enable_default) {
	return DECLINED;
    }

    /* Set defaut Cache-Control headers within this location */
    am_set_cache_control_headers(r);

    /* Check if this is a request for one of our endpoints. We check if
     * the uri starts with the path set with the MellonEndpointPath
     * configuration directive.
     */
    if(strstr(r->uri, dir->endpoint_path) == r->uri) {
        /* No access control on our internal endpoints. */
        return OK;
    }

    /* Get the session of this request. */
    session = am_get_request_session(r);


    if(dir->enable_mellon == am_enable_auth) {
        /* This page requires the user to be authenticated and authorized. */

        if(session == NULL || !session->logged_in) {
            /* We don't have a valid session. */

            if(session) {
                /* Release the session. */
                am_release_request_session(r, session);
            }

            /* Send the user to the authentication page on the IdP. */
            return am_start_auth(r);
        }

        /* Verify that the user has access to this resource. */
        return_code = am_check_permissions(r, session);
        if(return_code != OK) {
            am_release_request_session(r, session);

            return return_code;
        }


        /* The user has been authenticated, and we can now populate r->user
         * and the r->subprocess_env with values from the session store.
         */
        am_cache_env_populate(r, session);

        /* Release the session. */
        am_release_request_session(r, session);

        return OK;

    } else {
        /* dir->enable_mellon == am_enable_info:
         * We should pass information about the user to the web application
         * if the user is authorized to access this resource.
         * However, we shouldn't attempt to do any access control.
         */

        if(session != NULL
           && session->logged_in
           && am_check_permissions(r, session) == OK) {

            /* The user is authenticated and has access to the resource.
             * Now we populate the environment with information about
             * the user.
             */
            am_cache_env_populate(r, session);
        }

        if(session != NULL) {
            /* Release the session. */
            am_release_request_session(r, session);
        }

        /* We shouldn't really do any access control, so we always return
         * DECLINED.
         */
        return DECLINED;
    }
}


int am_check_uid(request_rec *r)
{
    am_dir_cfg_rec *dir = am_get_dir_cfg(r);
    am_cache_entry_t *session;
    int return_code = HTTP_UNAUTHORIZED;

    /* check if we are a subrequest.  if we are, then just return OK
     * without any checking since these cannot be injected (heh). */
    if (r->main)
        return OK;

    /* Check if this is a request for one of our endpoints. We check if
     * the uri starts with the path set with the MellonEndpointPath
     * configuration directive.
     */
    if(strstr(r->uri, dir->endpoint_path) == r->uri) {
        /* No access control on our internal endpoints. */
        return OK;
    }


    /* Get the session of this request. */
    session = am_get_request_session(r);

    /* If we don't have a session, then we can't authorize the user. */
    if(session == NULL) {
        return HTTP_UNAUTHORIZED;
    }

    /* If the user isn't logged in, then we can't authorize the user. */
    if(!session->logged_in) {
        am_release_request_session(r, session);
        return HTTP_UNAUTHORIZED;
    }

    /* Verify that the user has access to this resource. */
    return_code = am_check_permissions(r, session);
    if(return_code != OK) {
        am_release_request_session(r, session);
        return HTTP_UNAUTHORIZED;
    }

    /* The user has been authenticated, and we can now populate r->user
     *  and the r->subprocess_env with values from the session store.
     */
    am_cache_env_populate(r, session);

    /* Release the session. */
    am_release_request_session(r, session);

    return OK;
}