summaryrefslogtreecommitdiffstats
path: root/src/lib/radius.c
blob: b2de15b2524886fd1fa192f52a4754342d98e1a5 (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
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
/*
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *
 *   This library 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
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

/**
 * $Id$
 *
 * @file radius.c
 * @brief Functions to send/receive radius packets.
 *
 * @copyright 2000-2003,2006  The FreeRADIUS server project
 */

RCSID("$Id$")

#include	<freeradius-devel/libradius.h>

#include	<freeradius-devel/md5.h>
#include	<freeradius-devel/rfc4849.h>

#include	<fcntl.h>
#include	<ctype.h>

#ifdef WITH_UDPFROMTO
#include	<freeradius-devel/udpfromto.h>
#endif

/*
 *	Some messages get printed out only in debugging mode.
 */
#define FR_DEBUG_STRERROR_PRINTF if (fr_debug_lvl) fr_strerror_printf

#if 0
#define VP_TRACE printf

static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
{
	size_t i;

	printf("--- %s ---\n", msg);
	for (i = 0; i < len; i++) {
		if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
		printf("%02x ", data[i]);
		if ((i & 0x0f) == 0x0f) printf("\n");
	}
	if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
	fflush(stdout);
}

#else
#define VP_TRACE(_x, ...)
#define VP_HEXDUMP(_x, _y, _z)
#endif


/*
 *	The maximum number of attributes which we allow in an incoming
 *	request.  If there are more attributes than this, the request
 *	is rejected.
 *
 *	This helps to minimize the potential for a DoS, when an
 *	attacker spoofs Access-Request packets, which don't have a
 *	Message-Authenticator attribute.  This means that the packet
 *	is unsigned, and the attacker can use resources on the server,
 *	even if the end request is rejected.
 */
uint32_t fr_max_attributes = 0;
FILE *fr_log_fp = NULL;

typedef struct radius_packet_t {
  uint8_t	code;
  uint8_t	id;
  uint8_t	length[2];
  uint8_t	vector[AUTH_VECTOR_LEN];
  uint8_t	data[1];
} radius_packet_t;

static fr_randctx fr_rand_pool;	/* across multiple calls */
static int fr_rand_initialized = 0;
#ifndef WITH_RADIUSV11_ONLY
static unsigned int salt_offset = 0;
static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
#endif

char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
  "",					//!< 0
  "Access-Request",
  "Access-Accept",
  "Access-Reject",
  "Accounting-Request",
  "Accounting-Response",
  "Accounting-Status",
  "Password-Request",
  "Password-Accept",
  "Password-Reject",
  "Accounting-Message",			//!< 10
  "Access-Challenge",
  "Status-Server",
  "Status-Client",
  "14",
  "15",
  "16",
  "17",
  "18",
  "19",
  "20",					//!< 20
  "Resource-Free-Request",
  "Resource-Free-Response",
  "Resource-Query-Request",
  "Resource-Query-Response",
  "Alternate-Resource-Reclaim-Request",
  "NAS-Reboot-Request",
  "NAS-Reboot-Response",
  "28",
  "Next-Passcode",
  "New-Pin",				//!< 30
  "Terminate-Session",
  "Password-Expired",
  "Event-Request",
  "Event-Response",
  "35",
  "36",
  "37",
  "38",
  "39",
  "Disconnect-Request",			//!< 40
  "Disconnect-ACK",
  "Disconnect-NAK",
  "CoA-Request",
  "CoA-ACK",
  "CoA-NAK",
  "46",
  "47",
  "48",
  "49",
  "IP-Address-Allocate",
  "IP-Address-Release",			//!< 50
};


void fr_printf_log(char const *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	if ((fr_debug_lvl == 0) || !fr_log_fp) {
		va_end(ap);
		return;
	}

	vfprintf(fr_log_fp, fmt, ap);
	va_end(ap);

	return;
}

static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";

static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
{
	int i;

	for (i = 0; i < attrlen; i++) {
		if ((i > 0) && ((i & 0x0f) == 0x00))
			fprintf(fr_log_fp, "%.*s", depth, tabs);
		fprintf(fr_log_fp, "%02x ", ptr[i]);
		if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
	}
	if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
}


void rad_print_hex(RADIUS_PACKET const *packet)
{
	int i;

	if (!packet->data || !fr_log_fp) return;

	fprintf(fr_log_fp, "  Socket:\t%d\n", packet->sockfd);
#ifdef WITH_TCP
	fprintf(fr_log_fp, "  Proto:\t%d\n", packet->proto);
#endif

	if (packet->src_ipaddr.af == AF_INET) {
		char buffer[32];

		fprintf(fr_log_fp, "  Src IP:\t%s\n",
			inet_ntop(packet->src_ipaddr.af,
				  &packet->src_ipaddr.ipaddr,
				  buffer, sizeof(buffer)));
		fprintf(fr_log_fp, "    port:\t%u\n", packet->src_port);

		fprintf(fr_log_fp, "  Dst IP:\t%s\n",
			inet_ntop(packet->dst_ipaddr.af,
				  &packet->dst_ipaddr.ipaddr,
				  buffer, sizeof(buffer)));
		fprintf(fr_log_fp, "    port:\t%u\n", packet->dst_port);
	}

	if (packet->data[0] < FR_MAX_PACKET_CODE) {
		fprintf(fr_log_fp, "  Code:\t\t(%d) %s\n", packet->data[0], fr_packet_codes[packet->data[0]]);
	} else {
		fprintf(fr_log_fp, "  Code:\t\t%u\n", packet->data[0]);
	}
	fprintf(fr_log_fp, "  Id:\t\t%u\n", packet->data[1]);
	fprintf(fr_log_fp, "  Length:\t%u\n", ((packet->data[2] << 8) |
				   (packet->data[3])));
	fprintf(fr_log_fp, "  Vector:\t");
	for (i = 4; i < 20; i++) {
		fprintf(fr_log_fp, "%02x", packet->data[i]);
	}
	fprintf(fr_log_fp, "\n");

	if (packet->data_len > 20) {
		int total;
		uint8_t const *ptr;
		fprintf(fr_log_fp, "  Data:");

		total = packet->data_len - 20;
		ptr = packet->data + 20;

		while (total > 0) {
			int attrlen;
			unsigned int vendor = 0;

			fprintf(fr_log_fp, "\t\t");
			if (total < 2) { /* too short */
				fprintf(fr_log_fp, "%02x\n", *ptr);
				break;
			}

			if (ptr[1] > total) { /* too long */
				for (i = 0; i < total; i++) {
					fprintf(fr_log_fp, "%02x ", ptr[i]);
				}
				break;
			}

			fprintf(fr_log_fp, "%02x  %02x  ", ptr[0], ptr[1]);
			attrlen = ptr[1] - 2;

			if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
			    (attrlen > 4)) {
				vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
				fprintf(fr_log_fp, "%02x%02x%02x%02x (%u)  ",
				       ptr[2], ptr[3], ptr[4], ptr[5], vendor);
				attrlen -= 4;
				ptr += 6;
				total -= 6;

			} else {
				ptr += 2;
				total -= 2;
			}

			print_hex_data(ptr, attrlen, 3);

			ptr += attrlen;
			total -= attrlen;
		}
	}
	fflush(stdout);
}

/** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
 *
 */
static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
#ifdef WITH_UDPFROMTO
		      fr_ipaddr_t *src_ipaddr, uint16_t src_port,
#else
		      UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
#endif
		      fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
{
	int rcode;
	struct sockaddr_storage	dst;
	socklen_t		sizeof_dst;

#ifdef WITH_UDPFROMTO
	struct sockaddr_storage	src;
	socklen_t		sizeof_src;

	fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
#endif

	if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
		return -1;
	}

#ifdef WITH_UDPFROMTO
	/*
	 *	And if they don't specify a source IP address, don't
	 *	use udpfromto.
	 */
	if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
	    (src_ipaddr->af != AF_UNSPEC) &&
	    !fr_inaddr_any(src_ipaddr)) {
		rcode = sendfromto(sockfd, data, data_len, flags,
				   (struct sockaddr *)&src, sizeof_src,
				   (struct sockaddr *)&dst, sizeof_dst);
		goto done;
	}
#endif

	/*
	 *	No udpfromto, fail gracefully.
	 */
	rcode = sendto(sockfd, data, data_len, flags,
		       (struct sockaddr *) &dst, sizeof_dst);
#ifdef WITH_UDPFROMTO
done:
#endif
	if (rcode < 0) {
		fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
	}

	return rcode;
}


void rad_recv_discard(int sockfd)
{
	uint8_t			header[4];
	struct sockaddr_storage	src;
	socklen_t		sizeof_src = sizeof(src);

	(void) recvfrom(sockfd, header, sizeof(header), 0,
			(struct sockaddr *)&src, &sizeof_src);
}

/** Basic validation of RADIUS packet header
 *
 * @note fr_strerror errors are only available if fr_debug_lvl > 0. This is to reduce CPU time
 *	consumed when discarding malformed packet.
 *
 * @param[in] sockfd we're reading from.
 * @param[out] src_ipaddr of the packet.
 * @param[out] src_port of the packet.
 * @param[out] code Pointer to where to write the packet code.
 * @return
 *	- -1 on failure.
 *	- 1 on decode error.
 *	- >= RADIUS_HDR_LEN on success. This is the packet length as specified in the header.
 */
ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
{
	ssize_t			data_len, packet_len;
	uint8_t			header[4];
	struct sockaddr_storage	src;
	socklen_t		sizeof_src = sizeof(src);

	data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK, (struct sockaddr *)&src, &sizeof_src);
	if (data_len < 0) {
		if ((errno == EAGAIN) || (errno == EINTR)) return 0;
		return -1;
	}

	/*
	 *	Convert AF.  If unknown, discard packet.
	 */
	if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
		FR_DEBUG_STRERROR_PRINTF("Unknown address family");
		rad_recv_discard(sockfd);

		return 1;
	}

	/*
	 *	Too little data is available, discard the packet.
	 */
	if (data_len < 4) {
		FR_DEBUG_STRERROR_PRINTF("Expected at least 4 bytes of header data, got %zu bytes", data_len);
invalid:
		FR_DEBUG_STRERROR_PRINTF("Invalid data from %s: %s",
					 fr_inet_ntop(src_ipaddr->af, &src_ipaddr->ipaddr),
					 fr_strerror());
		rad_recv_discard(sockfd);

		return 1;
	}

	/*
	 *	See how long the packet says it is.
	 */
	packet_len = (header[2] * 256) + header[3];

	/*
	 *	The length in the packet says it's less than
	 *	a RADIUS header length: discard it.
	 */
	if (packet_len < RADIUS_HDR_LEN) {
		FR_DEBUG_STRERROR_PRINTF("Expected at least " STRINGIFY(RADIUS_HDR_LEN)  " bytes of packet "
					 "data, got %zu bytes", packet_len);
		goto invalid;
	}

	/*
	 *	Enforce RFC requirements, for sanity.
	 *	Anything after 4k will be discarded.
	 */
	if (packet_len > MAX_PACKET_LEN) {
		FR_DEBUG_STRERROR_PRINTF("Length field value too large, expected maximum of "
					 STRINGIFY(MAX_PACKET_LEN) " bytes, got %zu bytes", packet_len);
		goto invalid;
	}

	*code = header[0];

	/*
	 *	The packet says it's this long, but the actual UDP
	 *	size could still be smaller.
	 */
	return packet_len;
}


/** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
 *
 */
static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
			    fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
			    fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
{
	struct sockaddr_storage	src;
	struct sockaddr_storage	dst;
	socklen_t		sizeof_src = sizeof(src);
	socklen_t		sizeof_dst = sizeof(dst);
	ssize_t			data_len;
	size_t			len;
	uint16_t		port;
	uint8_t			buffer[MAX_PACKET_LEN];

	memset(&src, 0, sizeof_src);
	memset(&dst, 0, sizeof_dst);

	/*
	 *	Receive the packet.  The OS will discard any data in the
	 *	packet after "len" bytes.
	 */
#ifdef WITH_UDPFROMTO
	data_len = recvfromto(sockfd, buffer, sizeof(buffer), flags,
			      (struct sockaddr *)&src, &sizeof_src,
			      (struct sockaddr *)&dst, &sizeof_dst);
#else
	data_len = recvfrom(sockfd, buffer, sizeof(buffer), flags,
			    (struct sockaddr *)&src, &sizeof_src);

	/*
	 *	Get the destination address, too.
	 */
	if (getsockname(sockfd, (struct sockaddr *)&dst,
			&sizeof_dst) < 0) return -1;
#endif
	if (data_len <= 0) {
		return data_len;
	}

	/*
	 *      See how long the packet says it is.
	 */
	len = (buffer[2] * 256) + buffer[3];

	/*
	 *	Header says it's smaller than a RADIUS header, *or*
	 *	the RADIUS header says that the RADIUS packet islarger
	 *	than our buffer.  Discard it.
	 */
	if ((len < RADIUS_HDR_LEN) || (len > (size_t) data_len)) return 0;

	if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
		return -1;	/* Unknown address family, Die Die Die! */
	}
	*src_port = port;

	fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
	*dst_port = port;

	/*
	 *	Different address families should never happen.
	 */
	if (src.ss_family != dst.ss_family) {
		return -1;
	}

	packet->data = talloc_memdup(packet, buffer, len);
	if (!packet->data) return -1;

	packet->data_len = len;

	/*
	 *	Return the length of the RADIUS packet.  There may be
	 *	stuff after the end of the RADIUS packet, so we don't
	 *	want to parse that as RADIUS.
	 */
	return len;
}


#ifndef WITH_RADIUSV11_ONLY
#define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
/** Build an encrypted secret value to return in a reply packet
 *
 * The secret is hidden by xoring with a MD5 digest created from
 * the shared secret and the authentication vector.
 * We put them into MD5 in the reverse order from that used when
 * encrypting passwords to RADIUS.
 */
static void make_secret(uint8_t *digest, uint8_t const *vector,
			char const *secret, uint8_t const *value, size_t length)
{
	FR_MD5_CTX context;
	size_t	     i;

	fr_md5_init(&context);
	fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
	fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
	fr_md5_final(digest, &context);

	for ( i = 0; i < length; i++ ) {
		digest[i] ^= value[i];
	}

	fr_md5_destroy(&context);
}

#define MAX_PASS_LEN (128)
static void make_passwd(uint8_t *output, ssize_t *outlen,
			uint8_t const *input, size_t inlen,
			char const *secret, uint8_t const *vector)
{
	FR_MD5_CTX context, old;
	uint8_t	digest[AUTH_VECTOR_LEN];
	uint8_t passwd[MAX_PASS_LEN];
	size_t	i, n;
	size_t	len;

	/*
	 *	If the length is zero, round it up.
	 */
	len = inlen;

	if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;

	memcpy(passwd, input, len);
	if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);

	if (len == 0) {
		len = AUTH_PASS_LEN;
	}

	else if ((len & 0x0f) != 0) {
		len += 0x0f;
		len &= ~0x0f;
	}
	*outlen = len;

	fr_md5_init(&context);
	fr_md5_init(&old);
	fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
	fr_md5_copy(old, context);

	/*
	 *	Do first pass.
	 */
	fr_md5_update(&context, vector, AUTH_PASS_LEN);

	for (n = 0; n < len; n += AUTH_PASS_LEN) {
		if (n > 0) {
			fr_md5_copy(context, old);
			fr_md5_update(&context,
				       passwd + n - AUTH_PASS_LEN,
				       AUTH_PASS_LEN);
		}

		fr_md5_final(digest, &context);
		for (i = 0; i < AUTH_PASS_LEN; i++) {
			passwd[i + n] ^= digest[i];
		}
	}

	memcpy(output, passwd, len);

	fr_md5_destroy(&old);
	fr_md5_destroy(&context);
}


static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
			       uint8_t const *input, size_t inlen, size_t room,
			       char const *secret, uint8_t const *vector)
{
	FR_MD5_CTX context, old;
	uint8_t	digest[AUTH_VECTOR_LEN];
	size_t	i, n;
	size_t	encrypted_len;

	/*
	 *	The password gets encoded with a 1-byte "length"
	 *	field.  Ensure that it doesn't overflow.
	 */
	if (room > 253) room = 253;

	/*
	 *	Limit the maximum size of the input password.  2 bytes
	 *	are taken up by the salt, and one by the encoded
	 *	"length" field.  Note that if we have a tag, the
	 *	"room" will be 252 octets, not 253 octets.
	 */
	if (inlen > (room - 3)) inlen = room - 3;

	/*
	 *	Length of the encrypted data is the clear-text
	 *	password length plus one byte which encodes the length
	 *	of the password.  We round up to the nearest encoding
	 *	block.  Note that this can result in the encoding
	 *	length being more than 253 octets.
	 */
	encrypted_len = inlen + 1;
	if ((encrypted_len & 0x0f) != 0) {
		encrypted_len += 0x0f;
		encrypted_len &= ~0x0f;
	}

	/*
	 *	We need 2 octets for the salt, followed by the actual
	 *	encrypted data.
	 */
	if (encrypted_len > (room - 2)) encrypted_len = room - 2;

	*outlen = encrypted_len + 2;	/* account for the salt */

	/*
	 *	Copy the password over, and zero-fill the remainder.
	 */
	memcpy(output + 3, input, inlen);
	memset(output + 3 + inlen, 0, *outlen - 3 - inlen);

	/*
	 *	Generate salt.  The RFCs say:
	 *
	 *	The high bit of salt[0] must be set, each salt in a
	 *	packet should be unique, and they should be random
	 *
	 *	So, we set the high bit, add in a counter, and then
	 *	add in some CSPRNG data.  should be OK..
	 */
	output[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
		     (fr_rand() & 0x07));
	output[1] = fr_rand();
	output[2] = inlen;	/* length of the password string */

	fr_md5_init(&context);
	fr_md5_init(&old);
	fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
	fr_md5_copy(old, context);

	fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
	fr_md5_update(&context, &output[0], 2);

	for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
		size_t block_len;

		if (n > 0) {
			fr_md5_copy(context, old);
			fr_md5_update(&context,
				       output + 2 + n - AUTH_PASS_LEN,
				       AUTH_PASS_LEN);
		}

		fr_md5_final(digest, &context);

		if ((2 + n + AUTH_PASS_LEN) < room) {
			block_len = AUTH_PASS_LEN;
		} else {
			block_len = room - 2 - n;
		}

		for (i = 0; i < block_len; i++) {
			output[i + 2 + n] ^= digest[i];
		}
	}
	fr_md5_destroy(&old);
	fr_md5_destroy(&context);
}
#endif	/* WITH_RADIUSV11_ONLY */

static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
{
	unsigned int tlv1, tlv2;

	if (nest > fr_attr_max_tlv) return 0;

	if (!vp) return 0;

	/*
	 *	Keep encoding TLVs which have the same scope.
	 *	e.g. two attributes of:
	 *		ATTR.TLV1.TLV2.TLV3 = data1
	 *		ATTR.TLV1.TLV2.TLV4 = data2
	 *	both get put into a container of "ATTR.TLV1.TLV2"
	 */

	/*
	 *	Nothing to follow, we're done.
	 */
	if (!next) return 0;

	/*
	 *	Not from the same vendor, skip it.
	 */
	if (vp->da->vendor != next->da->vendor) return 0;

	/*
	 *	In a different TLV space, skip it.
	 */
	tlv1 = vp->da->attr;
	tlv2 = next->da->attr;

	tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
	tlv2 &= ((1 << fr_attr_shift[nest]) - 1);

	if (tlv1 != tlv2) return 0;

	return 1;
}


static ssize_t vp2data_any(RADIUS_PACKET const *packet,
			   RADIUS_PACKET const *original,
			   char const *secret, int nest,
			   VALUE_PAIR const **pvp,
			   uint8_t *start, size_t room);

static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
			   RADIUS_PACKET const *original,
			   char const *secret, VALUE_PAIR const **pvp,
			   unsigned int attribute, uint8_t *ptr, size_t room);

/** Encode the *data* portion of the TLV
 *
 * This is really a sub-function of vp2data_any().  It encodes the *data* portion
 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
 */
static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
			    RADIUS_PACKET const *original,
			    char const *secret, int nest,
			    VALUE_PAIR const **pvp,
			    uint8_t *start, size_t room)
{
	ssize_t len;
	size_t my_room;
	uint8_t *ptr = start;
	VALUE_PAIR const *vp = *pvp;
	VALUE_PAIR const *svp = vp;

	if (!svp) return 0;

#ifndef NDEBUG
	if (nest > fr_attr_max_tlv) {
		fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
		return -1;
	}
#endif

	while (vp) {
		VERIFY_VP(vp);

		if (room <= 2) return ptr - start;

		ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
		ptr[1] = 2;

		my_room = room;
		if (room > 255) my_room = 255;

		len = vp2data_any(packet, original, secret, nest,
				  &vp, ptr + 2, my_room - 2);
		if (len < 0) return len;
		if (len == 0) return ptr - start;
		/* len can NEVER be more than 253 */

		ptr[1] += len;

#ifndef NDEBUG
		if ((fr_debug_lvl > 3) && fr_log_fp) {
			fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
			print_hex_data(ptr + 2, len, 3);
		}
#endif

		room -= ptr[1];
		ptr += ptr[1];
		*pvp = vp;

		if (!do_next_tlv(svp, vp, nest)) break;
	}

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) {
		DICT_ATTR const *da;

		da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
		if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
	}
#endif

	return ptr - start;
}

/** Encodes the data portion of an attribute
 *
 * @return -1 on error, or the length of the data portion.
 */
static ssize_t vp2data_any(RADIUS_PACKET const *packet,
			   RADIUS_PACKET const *original,
			   char const *secret, int nest,
			   VALUE_PAIR const **pvp,
			   uint8_t *start, size_t room)
{
	uint32_t lvalue;
	ssize_t len;
	uint8_t const *data;
	uint8_t *ptr = start;
	uint8_t	array[4];
	uint64_t lvalue64;
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);

	/*
	 *	See if we need to encode a TLV.  The low portion of
	 *	the attribute has already been placed into the packer.
	 *	If there are still attribute bytes left, then go
	 *	encode them as TLVs.
	 *
	 *	If we cared about the stack, we could unroll the loop.
	 */
	if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
	    ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
		return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
				    start, room);
	}

	/*
	 *	Set up the default sources for the data.
	 */
	len = vp->vp_length;

	switch (vp->da->type) {
	case PW_TYPE_STRING:
	case PW_TYPE_OCTETS:
		data = vp->data.ptr;
		if (!data) return 0;
		break;

	case PW_TYPE_IFID:
	case PW_TYPE_IPV4_ADDR:
	case PW_TYPE_IPV6_ADDR:
	case PW_TYPE_IPV6_PREFIX:
	case PW_TYPE_IPV4_PREFIX:
	case PW_TYPE_ABINARY:
	case PW_TYPE_ETHERNET:	/* just in case */
		data = (uint8_t const *) &vp->data;
		break;

	case PW_TYPE_BYTE:
		len = 1;	/* just in case */
		array[0] = vp->vp_byte;
		data = array;
		break;

	case PW_TYPE_SHORT:
		len = 2;	/* just in case */
		array[0] = (vp->vp_short >> 8) & 0xff;
		array[1] = vp->vp_short & 0xff;
		data = array;
		break;

	case PW_TYPE_INTEGER:
		len = 4;	/* just in case */
		lvalue = htonl(vp->vp_integer);
		memcpy(array, &lvalue, sizeof(lvalue));
		data = array;
		break;

	case PW_TYPE_INTEGER64:
		len = 8;	/* just in case */
		lvalue64 = htonll(vp->vp_integer64);
		data = (uint8_t *) &lvalue64;
		break;

		/*
		 *  There are no tagged date attributes.
		 */
	case PW_TYPE_DATE:
		lvalue = htonl(vp->vp_date);
		data = (uint8_t const *) &lvalue;
		len = 4;	/* just in case */
		break;

	case PW_TYPE_SIGNED:
	{
		int32_t slvalue;

		len = 4;	/* just in case */
		slvalue = htonl(vp->vp_signed);
		memcpy(array, &slvalue, sizeof(slvalue));
		data = array;
		break;
	}

	default:		/* unknown type: ignore it */
		fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
		return -1;
	}

	/*
	 *	No data: skip it.
	 */
	if (len == 0) {
		*pvp = vp->next;
		return 0;
	}

	/*
	 *	Bound the data to the calling size
	 */
	if (len > (ssize_t) room) len = room;

#ifdef WITH_RADIUSV11
	/*
	 *	RADIUSV11 does not encrypt any attributes.
	 */
	if (packet->radiusv11) goto tag;
#endif

	/*
	 *	Encrypt the various password styles
	 *
	 *	Attributes with encrypted values MUST be less than
	 *	128 bytes long.
	 */
	switch (vp->da->flags.encrypt) {
#ifndef WITH_RADIUSV11_ONLY
	case FLAG_ENCRYPT_USER_PASSWORD:
		make_passwd(ptr, &len, data, len,
			    secret, packet->vector);
		break;

	case FLAG_ENCRYPT_TUNNEL_PASSWORD:
		lvalue = 0;
		if (vp->da->flags.has_tag) lvalue = 1;

		/*
		 *	Check if there's enough room.  If there isn't,
		 *	we discard the attribute.
		 *
		 *	This is ONLY a problem if we have multiple VSA's
		 *	in one Vendor-Specific, though.
		 */
		if (room < (18 + lvalue)) return 0;

		switch (packet->code) {
		case PW_CODE_ACCESS_ACCEPT:
		case PW_CODE_ACCESS_REJECT:
		case PW_CODE_ACCESS_CHALLENGE:
		default:
			if (!original) {
				fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
				return -1;
			}

			make_tunnel_passwd(ptr + lvalue, &len, data, len,
					   room - lvalue,
					   secret, original->vector);
			break;
		case PW_CODE_ACCOUNTING_REQUEST:
		case PW_CODE_DISCONNECT_REQUEST:
		case PW_CODE_COA_REQUEST:
			make_tunnel_passwd(ptr + lvalue, &len, data, len,
					   room - lvalue,
					   secret, packet->vector);
			break;
		}
		if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
		len += lvalue;
		break;

		/*
		 *	The code above ensures that this attribute
		 *	always fits.
		 */
	case FLAG_ENCRYPT_ASCEND_SECRET:
		if (len > AUTH_VECTOR_LEN) len = AUTH_VECTOR_LEN;
		make_secret(ptr, packet->vector, secret, data, len);
		len = AUTH_VECTOR_LEN;
		break;
#endif	/* WITH_RADIUSV11_ONLY */

	default:
#ifdef WITH_RADIUSV11
	tag:
#endif
		if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
			if (vp->da->type == PW_TYPE_STRING) {
				if (len > ((ssize_t) (room - 1))) len = room - 1;
				ptr[0] = vp->tag;
				ptr++;
			} else if (vp->da->type == PW_TYPE_INTEGER) {
				array[0] = vp->tag;
			} /* else it can't be any other type */
		}
		memcpy(ptr, data, len);
		break;
	} /* switch over encryption flags */

	*pvp = vp->next;
	return len + (ptr - start);
}

static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
			  uint8_t *ptr, int hdr_len, ssize_t len,
			  int flag_offset, int vsa_offset)
{
	int check_len = len - ptr[1];
	int total = len + hdr_len;

	/*
	 *	Pass 1: Check if the addition of the headers
	 *	overflows the available room.  If so, return
	 *	what we were capable of encoding.
	 */

	while (check_len > (255 - hdr_len)) {
		total += hdr_len;
		check_len -= (255 - hdr_len);
	}

	/*
	 *	Note that this results in a number of attributes maybe
	 *	being marked as "encoded", but which aren't in the
	 *	packet.  Oh well.  The solution is to fix the
	 *	"vp2data_any" function to take into account the header
	 *	lengths.
	 */
	if ((ptr + ptr[1] + total) > end) {
		return (ptr + ptr[1]) - start;
	}

	/*
	 *	Pass 2: Now that we know there's enough room,
	 *	re-arrange the data to form a set of valid
	 *	RADIUS attributes.
	 */
	while (1) {
		int sublen = 255 - ptr[1];

		if (len <= sublen) {
			break;
		}

		len -= sublen;
		memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
		memmove(ptr + 255, ptr, hdr_len);
		ptr[1] += sublen;
		if (vsa_offset) ptr[vsa_offset] += sublen;
		ptr[flag_offset] |= 0x80;

		ptr += 255;
		ptr[1] = hdr_len;
		if (vsa_offset) ptr[vsa_offset] = 3;
	}

	ptr[1] += len;
	if (vsa_offset) ptr[vsa_offset] += len;

	return (ptr + ptr[1]) - start;
}


/** Encode an "extended" attribute
 */
int rad_vp2extended(RADIUS_PACKET const *packet,
		    RADIUS_PACKET const *original,
		    char const *secret, VALUE_PAIR const **pvp,
		    uint8_t *ptr, size_t room)
{
	int len;
	int hdr_len;
	uint8_t *start = ptr;
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);

	if (!vp->da->flags.extended) {
		fr_strerror_printf("rad_vp2extended called for non-extended attribute");
		return -1;
	}

	/*
	 *	The attribute number is encoded into the upper 8 bits
	 *	of the vendor ID.
	 */
	ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;

	if (!vp->da->flags.long_extended) {
		if (room < 3) return 0;

		ptr[1] = 3;
		ptr[2] = vp->da->attr & fr_attr_mask[0];

	} else {
		if (room < 4) return 0;

		ptr[1] = 4;
		ptr[2] = vp->da->attr & fr_attr_mask[0];
		ptr[3] = 0;
	}

	/*
	 *	Only "flagged" attributes can be longer than one
	 *	attribute.
	 */
	if (!vp->da->flags.long_extended && (room > 255)) {
		room = 255;
	}

	/*
	 *	Handle EVS VSAs.
	 */
	if (vp->da->flags.evs) {
		uint8_t *evs = ptr + ptr[1];

		if (room < (size_t) (ptr[1] + 5)) return 0;

		ptr[2] = 26;

		evs[0] = 0;	/* always zero */
		evs[1] = (vp->da->vendor >> 16) & 0xff;
		evs[2] = (vp->da->vendor >> 8) & 0xff;
		evs[3] = vp->da->vendor & 0xff;
		evs[4] = vp->da->attr & fr_attr_mask[0];

		ptr[1] += 5;
	}
	hdr_len = ptr[1];

	len = vp2data_any(packet, original, secret, 0,
			  pvp, ptr + ptr[1], room - hdr_len);
	if (len <= 0) return len;

	/*
	 *	There may be more than 252 octets of data encoded in
	 *	the attribute.  If so, move the data up in the packet,
	 *	and copy the existing header over.  Set the "M" flag ONLY
	 *	after copying the rest of the data.
	 */
	if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
		return attr_shift(start, start + room, ptr, 4, len, 3, 0);
	}

	ptr[1] += len;

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) {
		int jump = 3;

		fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
		if (!vp->da->flags.long_extended) {
			fprintf(fr_log_fp, "%02x  ", ptr[2]);

		} else {
			fprintf(fr_log_fp, "%02x %02x  ", ptr[2], ptr[3]);
			jump = 4;
		}

		if (vp->da->flags.evs) {
			fprintf(fr_log_fp, "%02x%02x%02x%02x (%u)  %02x  ",
				ptr[jump], ptr[jump + 1],
				ptr[jump + 2], ptr[jump + 3],
				((ptr[jump + 1] << 16) |
				 (ptr[jump + 2] << 8) |
				 ptr[jump + 3]),
				ptr[jump + 4]);
			jump += 5;
		}

		print_hex_data(ptr + jump, len, 3);
	}
#endif

	return (ptr + ptr[1]) - start;
}


/** Encode a WiMAX attribute
 *
 */
int rad_vp2wimax(RADIUS_PACKET const *packet,
		 RADIUS_PACKET const *original,
		 char const *secret, VALUE_PAIR const **pvp,
		 uint8_t *ptr, size_t room)
{
	int len;
	uint32_t lvalue;
	int hdr_len;
	uint8_t *start = ptr;
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);

	/*
	 *	Double-check for WiMAX format.
	 */
	if (!vp->da->flags.wimax) {
		fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
		return -1;
	}

	/*
	 *	Not enough room for:
	 *		attr, len, vendor-id, vsa, vsalen, continuation
	 */
	if (room < 9) return 0;

	/*
	 *	Build the Vendor-Specific header
	 */
	ptr = start;
	ptr[0] = PW_VENDOR_SPECIFIC;
	ptr[1] = 9;
	lvalue = htonl(vp->da->vendor);
	memcpy(ptr + 2, &lvalue, 4);
	ptr[6] = (vp->da->attr & fr_attr_mask[1]);
	ptr[7] = 3;
	ptr[8] = 0;		/* continuation byte */

	hdr_len = 9;

	len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
			  room - hdr_len);
	if (len <= 0) return len;

	/*
	 *	There may be more than 252 octets of data encoded in
	 *	the attribute.  If so, move the data up in the packet,
	 *	and copy the existing header over.  Set the "C" flag
	 *	ONLY after copying the rest of the data.
	 */
	if (len > (255 - ptr[1])) {
		return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
	}

	ptr[1] += len;
	ptr[7] += len;

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) {
		fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  %02x %02x %02x   ",
		       ptr[0], ptr[1],
		       ptr[2], ptr[3], ptr[4], ptr[5],
		       (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
		       ptr[6], ptr[7], ptr[8]);
		print_hex_data(ptr + 9, len, 3);
	}
#endif

	return (ptr + ptr[1]) - start;
}

/** Encode an RFC format attribute, with the "concat" flag set
 *
 * If there isn't enough room in the packet, the data is
 * truncated to fit.
 */
static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
			      UNUSED RADIUS_PACKET const *original,
			      UNUSED char const *secret, VALUE_PAIR const **pvp,
			      unsigned int attribute, uint8_t *start, size_t room)
{
	uint8_t *ptr = start;
	uint8_t const *p;
	size_t len, left;
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);

	p = vp->vp_octets;
	len = vp->vp_length;

	while (len > 0) {
		if (room <= 2) break;

		ptr[0] = attribute;
		ptr[1] = 2;

		left = len;

		/* no more than 253 octets */
		if (left > 253) left = 253;

		/* no more than "room" octets */
		if (room < (left + 2)) left = room - 2;

		memcpy(ptr + 2, p, left);

#ifndef NDEBUG
		if ((fr_debug_lvl > 3) && fr_log_fp) {
			fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
			print_hex_data(ptr + 2, len, 3);
		}
#endif
		ptr[1] += left;
		ptr += ptr[1];
		p += left;
		room -= left;
		len -= left;
	}

	*pvp = vp->next;
	return ptr - start;
}

/** Encode an RFC format TLV.
 *
 * This could be a standard attribute, or a TLV data type.
 * If it's a standard attribute, then vp->da->attr == attribute.
 * Otherwise, attribute may be something else.
 */
static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
			   RADIUS_PACKET const *original,
			   char const *secret, VALUE_PAIR const **pvp,
			   unsigned int attribute, uint8_t *ptr, size_t room)
{
	ssize_t len;

	if (room <= 2) return 0;

	ptr[0] = attribute & 0xff;
	ptr[1] = 2;

	if (room > 255) room = 255;

	len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room - ptr[1]);
	if (len <= 0) return len;

	ptr[1] += len;

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) {
		fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
		print_hex_data(ptr + 2, len, 3);
	}
#endif

	return ptr[1];
}


/** Encode a VSA which is a TLV
 *
 * If it's in the RFC format, call vp2attr_rfc.  Otherwise, encode it here.
 */
static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
			   RADIUS_PACKET const *original,
			   char const *secret, VALUE_PAIR const **pvp,
			   unsigned int attribute, unsigned int vendor,
			   uint8_t *ptr, size_t room)
{
	ssize_t len;
	DICT_VENDOR *dv;
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);
	/*
	 *	Unknown vendor: RFC format.
	 *	Known vendor and RFC format: go do that.
	 */
	dv = dict_vendorbyvalue(vendor);
	if (!dv ||
	    (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
		return vp2attr_rfc(packet, original, secret, pvp,
				   attribute, ptr, room);
	}

	switch (dv->type) {
	default:
		fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
				   " type %u", (unsigned) dv->type);
		return -1;

	case 4:
		ptr[0] = 0;	/* attr must be 24-bit */
		ptr[1] = (attribute >> 16) & 0xff;
		ptr[2] = (attribute >> 8) & 0xff;
		ptr[3] = attribute & 0xff;
		break;

	case 2:
		ptr[0] = (attribute >> 8) & 0xff;
		ptr[1] = attribute & 0xff;
		break;

	case 1:
		ptr[0] = attribute & 0xff;
		break;
	}

	switch (dv->length) {
	default:
		fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
				   " length %u", (unsigned) dv->length);
		return -1;

	case 0:
		break;

	case 2:
		ptr[dv->type] = 0;
		ptr[dv->type + 1] = dv->type + 2;
		break;

	case 1:
		ptr[dv->type] = dv->type + 1;
		break;

	}

	if (room > 255) room = 255;

	len = vp2data_any(packet, original, secret, 0, pvp,
			  ptr + dv->type + dv->length, room - (dv->type + dv->length));
	if (len <= 0) return len;

	if (dv->length) ptr[dv->type + dv->length - 1] += len;

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) {
		switch (dv->type) {
		default:
			break;

		case 4:
			if ((fr_debug_lvl > 3) && fr_log_fp)
				fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
					ptr[0], ptr[1], ptr[2], ptr[3]);
			break;

		case 2:
			if ((fr_debug_lvl > 3) && fr_log_fp)
				fprintf(fr_log_fp, "\t\t%02x%02x ",
					ptr[0], ptr[1]);
		break;

		case 1:
			if ((fr_debug_lvl > 3) && fr_log_fp)
				fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
			break;
		}

		switch (dv->length) {
		default:
			break;

		case 0:
			fprintf(fr_log_fp, "  ");
			break;

		case 1:
			fprintf(fr_log_fp, "%02x  ",
				ptr[dv->type]);
			break;

		case 2:
			fprintf(fr_log_fp, "%02x%02x  ",
				ptr[dv->type], ptr[dv->type] + 1);
			break;
		}

		print_hex_data(ptr + dv->type + dv->length, len, 3);
	}
#endif

	return dv->type + dv->length + len;
}


/** Encode a Vendor-Specific attribute
 *
 */
int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
		char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
		size_t room)
{
	ssize_t len;
	uint32_t lvalue;
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);

	if (vp->da->vendor == 0) {
		fr_strerror_printf("rad_vp2vsa called with rfc attribute");
		return -1;
	}

	/*
	 *	Double-check for WiMAX format.
	 */
	if (vp->da->flags.wimax) {
		return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
	}

	if (vp->da->vendor > FR_MAX_VENDOR) {
		fr_strerror_printf("rad_vp2vsa: Invalid arguments");
		return -1;
	}

	/*
	 *	Not enough room for:
	 *		attr, len, vendor-id
	 */
	if (room < 6) return 0;

	/*
	 *	Build the Vendor-Specific header
	 */
	ptr[0] = PW_VENDOR_SPECIFIC;
	ptr[1] = 6;
	lvalue = htonl(vp->da->vendor);
	memcpy(ptr + 2, &lvalue, 4);

	if (room > 255) room = 255;

	len = vp2attr_vsa(packet, original, secret, pvp,
			  vp->da->attr, vp->da->vendor,
			  ptr + ptr[1], room - ptr[1]);
	if (len < 0) return len;

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) {
		fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  ",
		       ptr[0], ptr[1],
		       ptr[2], ptr[3], ptr[4], ptr[5],
		       (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
		print_hex_data(ptr + 6, len, 3);
	}
#endif

	ptr[1] += len;

	return ptr[1];
}


/** Encode an RFC standard attribute 1..255
 *
 */
int rad_vp2rfc(RADIUS_PACKET const *packet,
	       RADIUS_PACKET const *original,
	       char const *secret, VALUE_PAIR const **pvp,
	       uint8_t *ptr, size_t room)
{
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);

	if (room < 2) return -1;

	if (vp->da->vendor != 0) {
		fr_strerror_printf("rad_vp2rfc called with VSA");
		return -1;
	}

	if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
		fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
		return -1;
	}

	/*
	 *	Only CUI is allowed to have zero length.
	 *	Thank you, WiMAX!
	 */
	if ((vp->vp_length == 0) &&
	    (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
		ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
		ptr[1] = 2;

		*pvp = vp->next;
		return 2;
	}

	/*
	 *	Message-Authenticator is hard-coded.
	 */
	if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
#ifdef WITH_RADIUSV11
		/*
		 *	RADIUSV11 does not encode or verify Message-Authenticator.
		 */
		if (packet->radiusv11) {
			*pvp = (*pvp)->next;
			return 0;
		}
#endif

		if (room < 18) return -1;

		ptr[0] = PW_MESSAGE_AUTHENTICATOR;
		ptr[1] = 18;
		memset(ptr + 2, 0, 16);
#ifndef NDEBUG
		if ((fr_debug_lvl > 3) && fr_log_fp) {
			fprintf(fr_log_fp, "\t\t50 12 ...\n");
		}
#endif

		*pvp = (*pvp)->next;
		return 18;
	}

	/*
	 *	Hacks for NAS-Filter-Rule.  They all get concatenated
	 *	with 0x00 bytes in between the values.  We rely on the
	 *	decoder to do the opposite transformation on incoming
	 *	packets.
	 */
	if (vp->da->attr == PW_NAS_FILTER_RULE) {
		uint8_t const *end = ptr + room;
		uint8_t *p, *attr = ptr;
		bool zero = false;

		attr[0] = PW_NAS_FILTER_RULE;
		attr[1] = 2;
		p = ptr + 2;

		while (vp && !vp->da->vendor && (vp->da->attr == PW_NAS_FILTER_RULE)) {
			if ((p + zero + vp->vp_length) > end) {				
				break;
			}

			if (zero) {
				if (attr[1] == 255) {
					attr = p;
					if ((attr + 3) >= end) break;

					attr[0] = PW_NAS_FILTER_RULE;
					attr[1] = 2;
					p = attr + 2;
				}

				*(p++) = 0;
				attr[1]++;
			}

			/*
			 *	Check for overflow
			 */
			if ((attr[1] + vp->vp_length) < 255) {
				memcpy(p, vp->vp_strvalue, vp->vp_length);
				attr[1] += vp->vp_length;
				p += vp->vp_length;

			} else if (attr + (attr[1] + 2 + vp->vp_length) > end) {
				break;

			} else if (vp->vp_length > 253) {
				/*
				 *	Drop VPs which are too long.
				 *	We don't (yet) split one VP
				 *	across multiple attributes.
				 */
				vp = vp->next;
				continue;

			} else {
				size_t first, second;

				first = 255 - attr[1];
				second = vp->vp_length - first;

				memcpy(p, vp->vp_strvalue, first);
				p += first;
				attr[1] = 255;
				attr = p;

				attr[0] = PW_NAS_FILTER_RULE;
				attr[1] = 2;
				p = attr + 2;

				memcpy(p, vp->vp_strvalue + first, second);
				attr[1] += second;
				p += second;
			}

			vp = vp->next;
			zero = true;
		}

		*pvp = vp;
		return p - ptr;
	}

	/*
	 *	EAP-Message is special.
	 */
	if (vp->da->flags.concat && (vp->vp_length > 253)) {
		return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
				      ptr, room);
	}

	return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
			   ptr, room);
}

static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
			     RADIUS_PACKET const *original,
			     char const *secret, VALUE_PAIR const **pvp,
			     uint8_t *start, size_t room)
{
	ssize_t len;
	VALUE_PAIR const *vp = *pvp;

	VERIFY_VP(vp);

	if (!vp->da->flags.is_tlv) {
		fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
		return -1;
	}

	if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
		fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
		return -1;
	}

	if (room < 5) return 0;

	/*
	 *	Encode the first level of TLVs
	 */
	start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
	start[1] = 4;
	start[2] = vp->da->attr & fr_attr_mask[0];
	start[3] = 2;

	len = vp2data_any(packet, original, secret, 0, pvp,
			  start + 4, room - 4);
	if (len <= 0) return len;

	if (len > 253) {
		return -1;
	}

	start[1] += len;
	start[3] += len;

	return start[1];
}

/** Parse a data structure into a RADIUS attribute
 *
 */
int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
		char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
		size_t room)
{
	VALUE_PAIR const *vp;

	if (!pvp || !*pvp || !start || (room <= 2)) return -1;

	vp = *pvp;

	VERIFY_VP(vp);

	/*
	 *	RFC format attributes take the fast path.
	 */
	if (!vp->da->vendor) {
		if (vp->da->attr > 255) {
			*pvp = vp->next;
			return 0;
		}

		return rad_vp2rfc(packet, original, secret, pvp,
				  start, room);
	}

	if (vp->da->flags.extended) {
		return rad_vp2extended(packet, original, secret, pvp,
				       start, room);
	}

	/*
	 *	The upper 8 bits of the vendor number are the standard
	 *	space attribute which is a TLV.
	 */
	if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
		return rad_vp2rfctlv(packet, original, secret, pvp,
				     start, room);
	}

	if (vp->da->flags.wimax) {
		return rad_vp2wimax(packet, original, secret, pvp,
				    start, room);
	}

	return rad_vp2vsa(packet, original, secret, pvp, start, room);
}


/** Encode a packet
 *
 */
int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
	       char const *secret)
{
	radius_packet_t		*hdr;
	uint8_t			*ptr;
	uint16_t		total_length;
	int			len;
	VALUE_PAIR const	*reply;

	/*
	 *	A 4K packet, aligned on 64-bits.
	 */
	uint64_t	data[MAX_PACKET_LEN / sizeof(uint64_t)];

	/*
	 *	Double-check some things based on packet code.
	 */
	switch (packet->code) {
	case PW_CODE_ACCESS_ACCEPT:
	case PW_CODE_ACCESS_REJECT:
	case PW_CODE_ACCESS_CHALLENGE:
		if (!original) {
			fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
			return -1;
		}
		break;

		/*
		 *	These packet vectors start off as all zero.
		 */
	case PW_CODE_ACCOUNTING_REQUEST:
	case PW_CODE_DISCONNECT_REQUEST:
	case PW_CODE_COA_REQUEST:
		memset(packet->vector, 0, sizeof(packet->vector));
		break;

	default:
		break;
	}

	/*
	 *	Use memory on the stack, until we know how
	 *	large the packet will be.
	 */
	hdr = (radius_packet_t *) data;

	/*
	 *	Build standard header
	 */
	hdr->code = packet->code;

#ifdef WITH_RADIUSV11
	if (packet->radiusv11) {
		uint32_t id = packet->id;

		hdr->id = 0;

		id = htonl(id);
		memcpy(hdr->vector, &id, sizeof(id));
		memset(hdr->vector + sizeof(id), 0, sizeof(hdr->vector) - sizeof(id));
	} else
#endif
	{
		hdr->id = packet->id;

		memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
	}

	total_length = RADIUS_HDR_LEN;

	/*
	 *	Load up the configuration values for the user
	 */
	ptr = hdr->data;
	packet->offset = 0;

	/*
	 *	FIXME: Loop twice over the reply list.  The first time,
	 *	calculate the total length of data.  The second time,
	 *	allocate the memory, and fill in the VP's.
	 *
	 *	Hmm... this may be slower than just doing a small
	 *	memcpy.
	 */

	/*
	 *	Loop over the reply attributes for the packet.
	 */
	reply = packet->vps;
	while (reply) {
		size_t last_len, room;
		char const *last_name = NULL;

		VERIFY_VP(reply);

		/*
		 *	Ignore non-wire attributes, but allow extended
		 *	attributes.
		 */
		if ((reply->da->vendor == 0) &&
		    ((reply->da->attr & 0xFFFF) >= 256) &&
		    !reply->da->flags.extended && !reply->da->flags.long_extended) {
#ifndef NDEBUG
			/*
			 *	Permit the admin to send BADLY formatted
			 *	attributes with a debug build.
			 */
			if (reply->da->attr == PW_RAW_ATTRIBUTE) {
				memcpy(ptr, reply->vp_octets, reply->vp_length);
				len = reply->vp_length;
				reply = reply->next;
				goto next;
			}
#endif
			reply = reply->next;
			continue;
		}

#ifdef WITH_RADIUSV11
		/*
		 *	Do not encode Message-Authenticator for RADIUS/1.1
		 */
		if ((reply->da->vendor == 0) && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
			reply = reply->next;
			continue;
		}


		/*
		 *	Do not encode Original-Packet-Code for RADIUS/1.1
		 */
		if (reply->da->vendor == ((unsigned int) PW_EXTENDED_ATTRIBUTE_1 << 24) && (reply->da->attr == 4)) {
			reply = reply->next;
			continue;
		}
#endif

		/*
		 *	We allow zero-length strings in "unlang", but
		 *	skip them (except for CUI, thanks WiMAX!) on
		 *	all other attributes.
		 */
		if (reply->vp_length == 0) {
			if ((reply->da->vendor != 0) ||
			    ((reply->da->attr != PW_CHARGEABLE_USER_IDENTITY) &&
			     (reply->da->attr != PW_MESSAGE_AUTHENTICATOR))) {
				reply = reply->next;
				continue;
			}
		}

		/*
		 *	How much room do we have left?
		 */
		room = ((uint8_t *) data) + sizeof(data) - ptr;

		/*
		 *	Set the Message-Authenticator to the correct
		 *	length and initial value.
		 */
		if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
#ifdef WITH_RADIUSV11
			/*
			 *	RADIUSV11 does not encode or verify Message-Authenticator.
			 */
			if (packet->radiusv11) {
				reply = reply->next;
				continue;
			}
#endif

			if (room < 18) break;

			/*
			 *	Cache the offset to the
			 *	Message-Authenticator
			 */
			packet->offset = total_length;
			last_len = 16;
		} else {
			if (room < (2 + reply->vp_length)) break;

			last_len = reply->vp_length;
		}
		last_name = reply->da->name;

		/*
		 *	Note that this also checks "room", as the
		 *	attribute may be a VSA, etc.
		 */
		len = rad_vp2attr(packet, original, secret, &reply, ptr, room);
		if (len < 0) return -1;

		/*
		 *	Failed to encode the attribute, likely because
		 *	the packet is full.
		 */
		if (len == 0) {
			if (last_len != 0) {
				fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
				break;
			} else {
				fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
			}
		}

#ifndef NDEBUG
	next:			/* Used only for Raw-Attribute */
#endif
		ptr += len;
		total_length += len;
	} /* done looping over all attributes */

	/*
	 *	Fill in the rest of the fields, and copy the data over
	 *	from the local stack to the newly allocated memory.
	 *
	 *	Yes, all this 'memcpy' is slow, but it means
	 *	that we only allocate the minimum amount of
	 *	memory for a request.
	 */
	packet->data_len = total_length;
	packet->data = talloc_array(packet, uint8_t, packet->data_len);
	if (!packet->data) {
		fr_strerror_printf("Out of memory");
		return -1;
	}

	memcpy(packet->data, hdr, packet->data_len);
	hdr = (radius_packet_t *) packet->data;

	total_length = htons(total_length);
	memcpy(hdr->length, &total_length, sizeof(total_length));

	return 0;
}

#ifdef WITH_RADIUSV11_ONLY
#define RADIUSV11_UNUSED UNUSED
#else
#define RADIUSV11_UNUSED
#endif

/** Sign a previously encoded packet
 *
 */
int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
	     RADIUSV11_UNUSED char const *secret)
{
	radius_packet_t	*hdr = (radius_packet_t *)packet->data;

	if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
	    (packet->offset < 0)) {
		fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
		return -1;
	}

#ifdef WITH_RADIUSV11
	/*
	 *	RADIUSV11 uses the authenticator field for matching
	 *	requests to responses, and does not otherwise verify
	 *	it.
	 */
	if (packet->radiusv11) {
		return 0;
	}
#endif

	/*
	 *	It wasn't assigned an Id, this is bad!
	 */
	if (packet->id < 0) {
		fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
		return -1;
	}

	/*
	 *	Set up the authentication vector with zero, or with
	 *	the original vector, prior to signing.
	 */
	switch (packet->code) {
	case PW_CODE_ACCOUNTING_REQUEST:
	case PW_CODE_DISCONNECT_REQUEST:
	case PW_CODE_COA_REQUEST:
		memset(packet->vector, 0, AUTH_VECTOR_LEN);
		break;

	case PW_CODE_ACCESS_ACCEPT:
	case PW_CODE_ACCESS_REJECT:
	case PW_CODE_ACCESS_CHALLENGE:
	case PW_CODE_ACCOUNTING_RESPONSE:
	case PW_CODE_DISCONNECT_ACK:
	case PW_CODE_DISCONNECT_NAK:
	case PW_CODE_COA_ACK:
	case PW_CODE_COA_NAK:
		if (!original) {
			fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
			return -1;
		}
		memcpy(packet->vector, original->vector, AUTH_VECTOR_LEN);
		break;

	case PW_CODE_ACCESS_REQUEST:
	case PW_CODE_STATUS_SERVER:
	default:
		break;		/* packet->vector is already random bytes */
	}

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
#endif

#ifndef WITH_RADIUSV11_ONLY
	/*
	 *	If there's a Message-Authenticator, update it
	 *	now.
	 */
	if ((packet->offset > 0) && ((size_t) (packet->offset + 18) <= packet->data_len)) {
		uint8_t calc_auth_vector[AUTH_VECTOR_LEN];

		switch (packet->code) {
		case PW_CODE_ACCOUNTING_RESPONSE:
			if (original && original->code == PW_CODE_STATUS_SERVER) {
				goto do_ack;
			}
			/* FALL-THROUGH */

		case PW_CODE_ACCOUNTING_REQUEST:
		case PW_CODE_DISCONNECT_REQUEST:
		case PW_CODE_DISCONNECT_ACK:
		case PW_CODE_DISCONNECT_NAK:
		case PW_CODE_COA_REQUEST:
		case PW_CODE_COA_ACK:
		case PW_CODE_COA_NAK:
			memset(hdr->vector, 0, AUTH_VECTOR_LEN);
			break;

		do_ack:
		case PW_CODE_ACCESS_ACCEPT:
		case PW_CODE_ACCESS_REJECT:
		case PW_CODE_ACCESS_CHALLENGE:
			memcpy(hdr->vector, original->vector, AUTH_VECTOR_LEN);
			break;

		default:
			break;
		}

		/*
		 *	Set the authentication vector to zero,
		 *	calculate the HMAC, and put it
		 *	into the Message-Authenticator
		 *	attribute.
		 */
		fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
			    (uint8_t const *) secret, strlen(secret));
		memcpy(packet->data + packet->offset + 2,
		       calc_auth_vector, AUTH_VECTOR_LEN);
	}
#endif	/* WITH_RADIUSV11_ONLY */

	/*
	 *	Copy the request authenticator over to the packet.
	 */
	memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);

#ifndef WITH_RADIUSV11_ONLY
	/*
	 *	Switch over the packet code, deciding how to
	 *	sign the packet.
	 */
	switch (packet->code) {
		/*
		 *	Request packets are not signed, but
		 *	have a random authentication vector.
		 */
	case PW_CODE_ACCESS_REQUEST:
	case PW_CODE_STATUS_SERVER:
		break;

		/*
		 *	Reply packets are signed with the
		 *	authentication vector of the request.
		 */
	default:
		{
			uint8_t digest[16];

			FR_MD5_CTX	context;
			fr_md5_init(&context);
			fr_md5_update(&context, packet->data, packet->data_len);
			fr_md5_update(&context, (uint8_t const *) secret,
				     strlen(secret));
			fr_md5_final(digest, &context);
			fr_md5_destroy(&context);

			memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
			memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
			break;
		}
	}/* switch over packet codes */
#endif	 /* WITH_RADIUSV11_ONLY */

	return 0;
}

/** Reply to the request
 *
 * Also attach reply attribute value pairs and any user message provided.
 */
int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
	     char const *secret)
{
	/*
	 *	Maybe it's a fake packet.  Don't send it.
	 */
	if (!packet || (packet->sockfd < 0)) {
		return 0;
	}

	/*
	 *  First time through, allocate room for the packet
	 */
	if (!packet->data) {
		/*
		 *	Encode the packet.
		 */
		if (rad_encode(packet, original, secret) < 0) {
			return -1;
		}

		/*
		 *	Re-sign it, including updating the
		 *	Message-Authenticator.
		 */
		if (rad_sign(packet, original, secret) < 0) {
			return -1;
		}

		/*
		 *	If packet->data points to data, then we print out
		 *	the VP list again only for debugging.
		 */
	}

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
#endif

#ifdef WITH_TCP
	/*
	 *	If the socket is TCP, call write().  Calling sendto()
	 *	is allowed on some platforms, but it's not nice.  Even
	 *	worse, if UDPFROMTO is defined, we *can't* use it on
	 *	TCP sockets.  So... just call write().
	 */
	if (packet->proto == IPPROTO_TCP) {
		ssize_t rcode;

		rcode = write(packet->sockfd, packet->data, packet->data_len);
		if (rcode >= 0) return rcode;

		fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
		return -1;
	}
#endif

	/*
	 *	And send it on it's way.
	 */
	return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
			  &packet->src_ipaddr, packet->src_port,
			  &packet->dst_ipaddr, packet->dst_port);
}

/** Do a comparison of two authentication digests by comparing the FULL digest
 *
 * Otherwise, the server can be subject to timing attacks that allow attackers
 * find a valid message authenticator.
 *
 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
 */
int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
{
	int result = 0;
	size_t i;

	for (i = 0; i < length; i++) {
		result |= a[i] ^ b[i];
	}

	return result;		/* 0 is OK, !0 is !OK, just like memcmp */
}

#ifndef WITH_RADIUSV11_ONLY
/** Validates the requesting client NAS
 *
 * Calculates the request Authenticator based on the clients private key.
 */
static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
{
	uint8_t		digest[AUTH_VECTOR_LEN];
	FR_MD5_CTX		context;

	/*
	 *	Zero out the auth_vector in the received packet.
	 *	Then append the shared secret to the received packet,
	 *	and calculate the MD5 sum. This must be the same
	 *	as the original MD5 sum (packet->vector).
	 */
	memset(packet->data + 4, 0, AUTH_VECTOR_LEN);

	/*
	 *  MD5(packet + secret);
	 */
	fr_md5_init(&context);
	fr_md5_update(&context, packet->data, packet->data_len);
	fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
	fr_md5_final(digest, &context);
	fr_md5_destroy(&context);

	/*
	 *	Return 0 if OK, 2 if not OK.
	 */
	if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
	return 0;
}


/** Validates the requesting client NAS
 *
 * Calculates the response Authenticator based on the clients
 * private key.
 */
static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
			    char const *secret)
{
	uint8_t		calc_digest[AUTH_VECTOR_LEN];
	FR_MD5_CTX		context;

	/*
	 *	Very bad!
	 */
	if (original == NULL) {
		return 3;
	}

	/*
	 *  Copy the original vector in place.
	 */
	memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);

	/*
	 *  MD5(packet + secret);
	 */
	fr_md5_init(&context);
	fr_md5_update(&context, packet->data, packet->data_len);
	fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
	fr_md5_final(calc_digest, &context);
	fr_md5_destroy(&context);

	/*
	 *  Copy the packet's vector back to the packet.
	 */
	memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);

	/*
	 *	Return 0 if OK, 2 if not OK.
	 */
	if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
	return 0;
}
#endif	/* WITH_RADIUSV11_ONLY */

/** Check if a set of RADIUS formatted TLVs are OK
 *
 */
int rad_tlv_ok(uint8_t const *data, size_t length,
	       size_t dv_type, size_t dv_length)
{
	uint8_t const *end = data + length;

	VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);

	VP_HEXDUMP("tlv_ok", data, length);

	if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
		fr_strerror_printf("rad_tlv_ok: Invalid arguments");
		return -1;
	}

	while (data < end) {
		size_t attrlen;

		if ((data + dv_type + dv_length) > end) {
			fr_strerror_printf("Attribute header overflow");
			return -1;
		}

		switch (dv_type) {
		case 4:
			if ((data[0] == 0) && (data[1] == 0) &&
			    (data[2] == 0) && (data[3] == 0)) {
			zero:
				fr_strerror_printf("Invalid attribute 0");
				return -1;
			}

			if (data[0] != 0) {
				fr_strerror_printf("Invalid attribute > 2^24");
				return -1;
			}
			break;

		case 2:
			if ((data[0] == 0) && (data[1] == 0)) goto zero;
			break;

		case 1:
			/*
			 *	Zero is allowed, because the Colubris
			 *	people are dumb and use it.
			 */
			break;

		default:
			fr_strerror_printf("Internal sanity check failed");
			return -1;
		}

		switch (dv_length) {
		case 0:
			return 0;

		case 2:
			if (data[dv_type] != 0) {
				fr_strerror_printf("Attribute is longer than 256 octets");
				return -1;
			}
			/* FALL-THROUGH */
		case 1:
			attrlen = data[dv_type + dv_length - 1];
			break;


		default:
			fr_strerror_printf("Internal sanity check failed");
			return -1;
		}

		if (attrlen < (dv_type + dv_length)) {
			fr_strerror_printf("Attribute header has invalid length");
			return -1;
		}

		if (attrlen > length) {
			fr_strerror_printf("Attribute overflows container");
			return -1;
		}

		data += attrlen;
		length -= attrlen;
	}

	return 0;
}


/** See if the data pointed to by PTR is a valid RADIUS packet.
 *
 * Packet is not 'const * const' because we may update data_len, if there's more data
 * in the UDP packet than in the RADIUS packet.
 *
 * @param packet to check
 * @param flags to control decoding
 * @param reason if not NULL, will have the failure reason written to where it points.
 * @return bool, true on success, false on failure.
 */
bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
{
	uint8_t			*attr;
	size_t			totallen;
	int			count;
	radius_packet_t		*hdr;
	char			host_ipaddr[128];
#ifndef WITH_RADIUSV11_ONLY
	bool			require_ma = false;
	bool			seen_ma = false;
	bool			eap = false;
	bool			non_eap = false;
#endif
	uint32_t		num_attributes;
	decode_fail_t		failure = DECODE_FAIL_NONE;

	/*
	 *	Check for packets smaller than the packet header.
	 *
	 *	RFC 2865, Section 3., subsection 'length' says:
	 *
	 *	"The minimum length is 20 ..."
	 */
	if (packet->data_len < RADIUS_HDR_LEN) {
		FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)),
				     packet->data_len, RADIUS_HDR_LEN);
		failure = DECODE_FAIL_MIN_LENGTH_PACKET;
		goto finish;
	}


	/*
	 *	Check for packets with mismatched size.
	 *	i.e. We've received 128 bytes, and the packet header
	 *	says it's 256 bytes long.
	 */
	totallen = (packet->data[2] << 8) | packet->data[3];
	hdr = (radius_packet_t *)packet->data;

	/*
	 *	Code of 0 is not understood.
	 *	Code of 16 or greate is not understood.
	 */
	if ((hdr->code == 0) ||
	    (hdr->code >= FR_MAX_PACKET_CODE)) {
		FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)),
			   hdr->code);
		failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
		goto finish;
	}

	/*
	 *	Message-Authenticator is required in Status-Server
	 *	packets, otherwise they can be trivially forged.
	 */
	if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;

	/*
	 *	It's also required if the caller asks for it.
	 */
	if (flags) require_ma = true;

	/*
	 *	Repeat the length checks.  This time, instead of
	 *	looking at the data we received, look at the value
	 *	of the 'length' field inside of the packet.
	 *
	 *	Check for packets smaller than the packet header.
	 *
	 *	RFC 2865, Section 3., subsection 'length' says:
	 *
	 *	"The minimum length is 20 ..."
	 */
	if (totallen < RADIUS_HDR_LEN) {
		FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)),
				     totallen, RADIUS_HDR_LEN);
		failure = DECODE_FAIL_MIN_LENGTH_FIELD;
		goto finish;
	}

	/*
	 *	And again, for the value of the 'length' field.
	 *
	 *	RFC 2865, Section 3., subsection 'length' says:
	 *
	 *	" ... and maximum length is 4096."
	 *
	 *	HOWEVER.  This requirement is for the network layer.
	 *	If the code gets here, we assume that a well-formed
	 *	packet is an OK packet.
	 *
	 *	We allow both the UDP data length, and the RADIUS
	 *	"length" field to contain up to 64K of data.
	 */

	/*
	 *	RFC 2865, Section 3., subsection 'length' says:
	 *
	 *	"If the packet is shorter than the Length field
	 *	indicates, it MUST be silently discarded."
	 *
	 *	i.e. No response to the NAS.
	 */
	if (packet->data_len < totallen) {
		FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)),
				     packet->data_len, totallen);
		failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
		goto finish;
	}

	/*
	 *	RFC 2865, Section 3., subsection 'length' says:
	 *
	 *	"Octets outside the range of the Length field MUST be
	 *	treated as padding and ignored on reception."
	 */
	if (packet->data_len > totallen) {
		/*
		 *	We're shortening the packet below, but just
		 *	to be paranoid, zero out the extra data.
		 */
		memset(packet->data + totallen, 0, packet->data_len - totallen);
		packet->data_len = totallen;
	}

	/*
	 *	Walk through the packet's attributes, ensuring that
	 *	they add up EXACTLY to the size of the packet.
	 *
	 *	If they don't, then the attributes either under-fill
	 *	or over-fill the packet.  Any parsing of the packet
	 *	is impossible, and will result in unknown side effects.
	 *
	 *	This would ONLY happen with buggy RADIUS implementations,
	 *	or with an intentional attack.  Either way, we do NOT want
	 *	to be vulnerable to this problem.
	 */
	attr = hdr->data;
	count = totallen - RADIUS_HDR_LEN;
	num_attributes = 0;

	while (count > 0) {
		/*
		 *	We need at least 2 bytes to check the
		 *	attribute header.
		 */
		if (count < 2) {
			FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
				   inet_ntop(packet->src_ipaddr.af,
					     &packet->src_ipaddr.ipaddr,
					     host_ipaddr, sizeof(host_ipaddr)));
			failure = DECODE_FAIL_HEADER_OVERFLOW;
			goto finish;
		}

		/*
		 *	Attribute number zero is NOT defined.
		 */
		if (attr[0] == 0) {
			FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
				   inet_ntop(packet->src_ipaddr.af,
					     &packet->src_ipaddr.ipaddr,
					     host_ipaddr, sizeof(host_ipaddr)));
			failure = DECODE_FAIL_INVALID_ATTRIBUTE;
			goto finish;
		}

		/*
		 *	Attributes are at LEAST as long as the ID & length
		 *	fields.  Anything shorter is an invalid attribute.
		 */
		if (attr[1] < 2) {
			FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
				   inet_ntop(packet->src_ipaddr.af,
					     &packet->src_ipaddr.ipaddr,
					     host_ipaddr, sizeof(host_ipaddr)),
				   attr[0]);
			failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
			goto finish;
		}

		/*
		 *	If there are fewer bytes in the packet than in the
		 *	attribute, it's a bad packet.
		 */
		if (count < attr[1]) {
			FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
				   inet_ntop(packet->src_ipaddr.af,
					     &packet->src_ipaddr.ipaddr,
					     host_ipaddr, sizeof(host_ipaddr)),
					   attr[0]);
			failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
			goto finish;
		}

#ifndef WITH_RADIUSV11_ONLY
		/*
		 *	Sanity check the attributes for length.
		 */
		switch (attr[0]) {
		default:	/* don't do anything by default */
			break;

			/*
			 *	If there's an EAP-Message, we require
			 *	a Message-Authenticator.
			 */
		case PW_EAP_MESSAGE:
			require_ma = true;
			eap = true;
			break;

		case PW_USER_PASSWORD:
		case PW_CHAP_PASSWORD:
		case PW_ARAP_PASSWORD:
			non_eap = true;
			break;

		case PW_MESSAGE_AUTHENTICATOR:
#ifdef WITH_RADIUSV11
			/*
			 *	RADIUSV11 does not encode or verify Message-Authenticator.
			 */
			if (packet->radiusv11) break;
#endif

			if (attr[1] != 2 + AUTH_VECTOR_LEN) {
				FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
					   inet_ntop(packet->src_ipaddr.af,
						     &packet->src_ipaddr.ipaddr,
						     host_ipaddr, sizeof(host_ipaddr)),
					   attr[1] - 2);
				failure = DECODE_FAIL_MA_INVALID_LENGTH;
				goto finish;
			}
			seen_ma = true;
			break;
		}
#endif

		/*
		 *	FIXME: Look up the base 255 attributes in the
		 *	dictionary, and switch over their type.  For
		 *	integer/date/ip, the attribute length SHOULD
		 *	be 6.
		 */
		count -= attr[1];	/* grab the attribute length */
		attr += attr[1];
		num_attributes++;	/* seen one more attribute */
	}

	/*
	 *	If the attributes add up to a packet, it's allowed.
	 *
	 *	If not, we complain, and throw the packet away.
	 */
	if (count != 0) {
		FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)));
		failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
		goto finish;
	}

	/*
	 *	If we're configured to look for a maximum number of
	 *	attributes, and we've seen more than that maximum,
	 *	then throw the packet away, as a possible DoS.
	 */
	if ((fr_max_attributes > 0) &&
	    (num_attributes > fr_max_attributes)) {
		FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)),
			   num_attributes, fr_max_attributes);
		failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
		goto finish;
	}

	/*
	 * 	http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
	 *
	 *	A packet with an EAP-Message attribute MUST also have
	 *	a Message-Authenticator attribute.
	 *
	 *	A Message-Authenticator all by itself is OK, though.
	 *
	 *	Similarly, Status-Server packets MUST contain
	 *	Message-Authenticator attributes.
	 */
	if (require_ma &&
#ifdef WITH_RADIUSV11
	    /*
	     *	RADIUSV11 does not encode or verify Message-Authenticator.
	     */
	    !packet->radiusv11 &&
#endif
	    !seen_ma) {
		FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)));
		failure = DECODE_FAIL_MA_MISSING;
		goto finish;
	}

#ifndef WITH_RADIUSV11_ONLY
	if (eap && non_eap) {
		FR_DEBUG_STRERROR_PRINTF("Bad packet from host %s:  Packet contains EAP-Message and non-EAP authentication attribute",
			   inet_ntop(packet->src_ipaddr.af,
				     &packet->src_ipaddr.ipaddr,
				     host_ipaddr, sizeof(host_ipaddr)));
		failure = DECODE_FAIL_TOO_MANY_AUTH;
		goto finish;
	}
#endif

	/*
	 *	Fill RADIUS header fields
	 */
	packet->code = hdr->code;
	packet->id = hdr->id;
#ifdef WITH_RADIUSV11
	if (packet->radiusv11) {
		uint32_t id;

		memcpy(&id, hdr->vector, sizeof(id));
		packet->id = ntohl(id);
	}
#endif
	memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);


	finish:

	if (reason) {
		*reason = failure;
	}
	return (failure == DECODE_FAIL_NONE);
}


/** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
 *
 */
RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
{
	int sock_flags = 0;
	ssize_t data_len;
	RADIUS_PACKET		*packet;

	/*
	 *	Allocate the new request data structure
	 */
	packet = rad_alloc(ctx, false);
	if (!packet) {
		fr_strerror_printf("out of memory");
		return NULL;
	}

	if (flags & 0x02) {
		sock_flags = MSG_PEEK;
		flags &= ~0x02;
	}

	data_len = rad_recvfrom(fd, packet, sock_flags,
				&packet->src_ipaddr, &packet->src_port,
				&packet->dst_ipaddr, &packet->dst_port);

	/*
	 *	Check for socket errors.
	 */
	if (data_len < 0) {
		FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
		/* packet->data is NULL */
		rad_free(&packet);
		return NULL;
	}

	/*
	 *	No data read from the network.
	 */
	if (data_len == 0) {
		rad_free(&packet);
		return NULL;
	}

	/*
	 *	See if it's a well-formed RADIUS packet.
	 */
	if (!rad_packet_ok(packet, flags, NULL)) {
		rad_free(&packet);
		return NULL;
	}

	/*
	 *	Remember which socket we read the packet from.
	 */
	packet->sockfd = fd;

	/*
	 *	FIXME: Do even more filtering by only permitting
	 *	certain IP's.  The problem is that we don't know
	 *	how to do this properly for all possible clients...
	 */

	/*
	 *	Explicitely set the VP list to empty.
	 */
	packet->vps = NULL;

#ifndef NDEBUG
	if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
#endif

	return packet;
}


/** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
 *
 */
int rad_verify(RADIUS_PACKET *packet, RADIUSV11_UNUSED RADIUS_PACKET *original, RADIUSV11_UNUSED char const *secret)
{
	uint8_t		*ptr;
	int		length;
	int		attrlen;
#ifndef WITH_RADIUSV11_ONLY
	int		rcode;
#endif
	char		buffer[32];

	if (!packet || !packet->data) return -1;

#ifdef WITH_RADIUSV11
	/*
	 *	RADIUSV11 uses the authenticator field for matching
	 *	requests to responses, and does not otherwise verify
	 *	it.
	 */
	if (packet->radiusv11) {
		return 0;
	}
#endif

	/*
	 *	Before we allocate memory for the attributes, do more
	 *	sanity checking.
	 */
	ptr = packet->data + RADIUS_HDR_LEN;
	length = packet->data_len - RADIUS_HDR_LEN;
	while (length > 0) {
#ifndef WITH_RADIUSV11_ONLY
		uint8_t	msg_auth_vector[AUTH_VECTOR_LEN];
		uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
#endif

		attrlen = ptr[1];

#ifndef WITH_RADIUSV11_ONLY
		switch (ptr[0]) {
		default:	/* don't do anything. */
			break;

			/*
			 *	Note that more than one Message-Authenticator
			 *	attribute is invalid.
			 */
		case PW_MESSAGE_AUTHENTICATOR:
#ifdef WITH_RADIUSV11
			/*
			 *	Ignore Message-Authenticator for RADIUSV11 packets.
			 */
			if (packet->radiusv11) break;
#endif

			memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
			memset(&ptr[2], 0, AUTH_VECTOR_LEN);

			switch (packet->code) {
			default:
				break;

			case PW_CODE_ACCOUNTING_RESPONSE:
				if (original &&
				    (original->code == PW_CODE_STATUS_SERVER)) {
					goto do_ack;
				}
				/* FALL-THROUGH */

			case PW_CODE_ACCOUNTING_REQUEST:
			case PW_CODE_DISCONNECT_REQUEST:
			case PW_CODE_COA_REQUEST:
				memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
				break;

			do_ack:
			case PW_CODE_ACCESS_ACCEPT:
			case PW_CODE_ACCESS_REJECT:
			case PW_CODE_ACCESS_CHALLENGE:
			case PW_CODE_DISCONNECT_ACK:
			case PW_CODE_DISCONNECT_NAK:
			case PW_CODE_COA_ACK:
			case PW_CODE_COA_NAK:
				if (!original) {
					fr_strerror_printf("Cannot validate Message-Authenticator in response "
							   "packet without a request packet");
					return -1;
				}
				memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
				break;
			}

			fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
				    (uint8_t const *) secret, strlen(secret));
			if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
				   sizeof(calc_auth_vector)) != 0) {
				fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  "
						   "(Shared secret is incorrect.)",
						   inet_ntop(packet->src_ipaddr.af,
							     &packet->src_ipaddr.ipaddr,
							     buffer, sizeof(buffer)));
				/* Silently drop packet, according to RFC 3579 */
				return -1;
			} /* else the message authenticator was good */

			/*
			 *	Reinitialize Authenticators.
			 */
			memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
			memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
			break;
		} /* switch over the attributes */
#endif		  /* WITH_RADIUSV11_ONLY */

		ptr += attrlen;
		length -= attrlen;
	} /* loop over the packet, sanity checking the attributes */

	/*
	 *	It looks like a RADIUS packet, but we don't know what it is
	 *	so can't validate the authenticators.
	 */
	if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
		fr_strerror_printf("Received Unknown packet code %d "
				   "from client %s port %d: Cannot validate Request/Response Authenticator.",
				   packet->code,
				   inet_ntop(packet->src_ipaddr.af,
				             &packet->src_ipaddr.ipaddr,
				             buffer, sizeof(buffer)),
				   packet->src_port);
		return -1;
	}

#ifndef WITH_RADIUSV11_ONLY
#ifdef WITH_RADIUSV11
	/*
	 *	RADIUSV11 uses the authenticator field for matching
	 *	requests to responses, and does not otherwise verify
	 *	it.
	 */
	if (packet->radiusv11) return 0;
#endif

	/*
	 *	Calculate and/or verify Request or Response Authenticator.
	 */
	switch (packet->code) {
	case PW_CODE_ACCESS_REQUEST:
	case PW_CODE_STATUS_SERVER:
		/*
		 *	The authentication vector is random
		 *	nonsense, invented by the client.
		 */
		break;

	case PW_CODE_COA_REQUEST:
	case PW_CODE_DISCONNECT_REQUEST:
	case PW_CODE_ACCOUNTING_REQUEST:
		if (calc_acctdigest(packet, secret) > 1) {
			fr_strerror_printf("Received %s packet "
					   "from client %s with invalid Request Authenticator!  "
					   "(Shared secret is incorrect.)",
					   fr_packet_codes[packet->code],
					   inet_ntop(packet->src_ipaddr.af,
						     &packet->src_ipaddr.ipaddr,
						     buffer, sizeof(buffer)));
			return -1;
		}
		break;

		/* Verify the reply digest */
	case PW_CODE_ACCESS_ACCEPT:
	case PW_CODE_ACCESS_REJECT:
	case PW_CODE_ACCESS_CHALLENGE:
	case PW_CODE_ACCOUNTING_RESPONSE:
	case PW_CODE_DISCONNECT_ACK:
	case PW_CODE_DISCONNECT_NAK:
	case PW_CODE_COA_ACK:
	case PW_CODE_COA_NAK:
		rcode = calc_replydigest(packet, original, secret);
		if (rcode > 1) {
			fr_strerror_printf("Received %s packet "
					   "from home server %s port %d with invalid Response Authenticator!  "
					   "(Shared secret is incorrect.)",
					   fr_packet_codes[packet->code],
					   inet_ntop(packet->src_ipaddr.af,
						     &packet->src_ipaddr.ipaddr,
						     buffer, sizeof(buffer)),
					   packet->src_port);
			return -1;
		}
		break;

	default:
		fr_strerror_printf("Received Unknown packet code %d "
				   "from client %s port %d: Cannot validate Request/Response Authenticator",
				   packet->code,
				   inet_ntop(packet->src_ipaddr.af,
				             &packet->src_ipaddr.ipaddr,
				             buffer, sizeof(buffer)),
				   packet->src_port);
		return -1;
	}
#endif

	return 0;
}


/** Convert one or more NAS-Filter-Rule attributes to one or more
 * attributes.
 *
 */
static ssize_t data2vp_nas_filter_rule(TALLOC_CTX *ctx,
				       DICT_ATTR const *da, uint8_t const *start,
				       size_t const packetlen, VALUE_PAIR **pvp)
{
	uint8_t const *p = start;
	uint8_t const *attr = start;
	uint8_t const *end = start + packetlen;
	uint8_t const *attr_end;
	uint8_t *q;
	VALUE_PAIR *vp;
	uint8_t buffer[253];

	q = buffer;

	/*
	 *	The packet has already been sanity checked, so we
	 *	don't care about walking off of the end of it.
	 */
	while (attr < end) {
		if ((attr + 2) > end) {
			fr_strerror_printf("decode NAS-Filter-Rule: Failure (1) to call rad_packet_ok");
			return -1;
		}

		if (attr[1] < 2) {
			fr_strerror_printf("decode NAS-Filter-Rule: Failure (2) to call rad_packet_ok");
			return -1;
		}
		if (attr[0] != PW_NAS_FILTER_RULE) break;

		/*
		 *	Now decode one, or part of one rule.
		 */
		p = attr + 2;
		attr_end = attr + attr[1];

		if (attr_end > end) {
			fr_strerror_printf("decode NAS-Filter-Rule: Failure (3) to call rad_packet_ok");
			return -1;
		}

		/*
		 *	Coalesce data until the zero byte.
		 */
		while (p < attr_end) {
			/*
			 *	Once we hit the zero byte, create the
			 *	VP, skip the zero byte, and reset the
			 *	counters.
			 */
			if (*p == 0) {
				/*
				 *	Discard consecutive zeroes.
				 */
				if (q > buffer) {
					vp = fr_pair_afrom_da(ctx, da);
					if (!vp) {
						fr_strerror_printf("decode NAS-Filter-Rule: Out of memory");
						return -1;
					}

					fr_pair_value_bstrncpy(vp, buffer, q - buffer);

					*pvp = vp;
					pvp = &(vp->next);
					q = buffer;
				}

				p++;
				continue;
			}
			*(q++) = *(p++);

			/*
			 *	Not much reason to have rules which
			 *	are too long.
			 */
			if ((size_t) (q - buffer) > sizeof(buffer)) {
				fr_strerror_printf("decode NAS-Filter-Rule: decoded attribute is too long");
				return -1;
			}
		}

		/*
		 *	Done this attribute.  There MAY be things left
		 *	in the buffer.
		 */
		attr = attr_end;
	}

	if (q == buffer) return attr + attr[2] - start;

	vp = fr_pair_afrom_da(ctx, da);
	if (!vp) {
		fr_strerror_printf("decode NAS-Filter-Rule: Out of memory");
		return -1;
	}
				
	fr_pair_value_bstrncpy(vp, buffer, q - buffer);

	*pvp = vp;

	return p - start;
}

/** Convert a "concatenated" attribute to one long VP
 *
 */
static ssize_t data2vp_concat(TALLOC_CTX *ctx,
			      DICT_ATTR const *da, uint8_t const *start,
			      size_t const packetlen, VALUE_PAIR **pvp)
{
	size_t total;
	uint8_t attr;
	uint8_t const *ptr = start;
	uint8_t const *end = start + packetlen;
	uint8_t *p;
	VALUE_PAIR *vp;

	total = 0;
	attr = ptr[0];

	/*
	 *	The packet has already been sanity checked, so we
	 *	don't care about walking off of the end of it.
	 */
	while (ptr < end) {
		if (ptr[1] < 2) return -1;
		if ((ptr + ptr[1]) > end) return -1;

		total += ptr[1] - 2;

		ptr += ptr[1];

		if (ptr == end) break;

		/*
		 *	Attributes MUST be consecutive.
		 */
		if (ptr[0] != attr) break;
	}

	end = ptr;

	vp = fr_pair_afrom_da(ctx, da);
	if (!vp) return -1;

	vp->vp_length = total;
	vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
	if (!p) {
		fr_pair_list_free(&vp);
		return -1;
	}

	total = 0;
	ptr = start;
	while (ptr < end) {
		memcpy(p, ptr + 2, ptr[1] - 2);
		p += ptr[1] - 2;
		total += ptr[1] - 2;
		ptr += ptr[1];
	}

	*pvp = vp;

	return ptr - start;
}


/** Convert TLVs to one or more VPs
 *
 */
ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
			    RADIUS_PACKET *packet, RADIUS_PACKET const *original,
			    char const *secret, DICT_ATTR const *da,
			    uint8_t const *start, size_t length,
			    VALUE_PAIR **pvp)
{
	uint8_t const *data = start;
	DICT_ATTR const *child;
	VALUE_PAIR *head, **tail;

	if (length < 3) return -1; /* type, length, value */

	VP_HEXDUMP("tlvs", data, length);

	if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;

	head = NULL;
	tail = &head;

	while (data < (start + length)) {
		ssize_t tlv_len;

		child = dict_attrbyparent(da, data[0], da->vendor);
		if (!child) {
			unsigned int my_attr, my_vendor;

			VP_TRACE("Failed to find child %u of TLV %s\n",
				 data[0], da->name);

			/*
			 *	Get child attr/vendor so that
			 *	we can call unknown attr.
			 */
			my_attr = data[0];
			my_vendor = da->vendor;

			if (!dict_attr_child(da, &my_attr, &my_vendor)) {
				fr_pair_list_free(&head);
				return -1;
			}

			child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
			if (!child) {
				fr_pair_list_free(&head);
				return -1;
			}
		}

		tlv_len = data2vp(ctx, packet, original, secret, child,
				  data + 2, data[1] - 2, data[1] - 2, tail);
		if (tlv_len < 0) {
			fr_pair_list_free(&head);
			return -1;
		}
		if (*tail) tail = &((*tail)->next);
		data += data[1];
	}

	*pvp = head;
	return length;
}

/** Convert a top-level VSA to a VP.
 *
 * "length" can be LONGER than just this sub-vsa.
 */
static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
			   RADIUS_PACKET const *original,
			   char const *secret, DICT_VENDOR *dv,
			   uint8_t const *data, size_t length,
			   VALUE_PAIR **pvp)
{
	unsigned int attribute;
	ssize_t attrlen, my_len;
	DICT_ATTR const *da;

	VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);

#ifndef NDEBUG
	if (length <= (dv->type + dv->length)) {
		fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
		return -1;
	}
#endif

	switch (dv->type) {
	case 4:
		/* data[0] must be zero */
		attribute = data[1] << 16;
		attribute |= data[2] << 8;
		attribute |= data[3];
		break;

	case 2:
		attribute = data[0] << 8;
		attribute |= data[1];
		break;

	case 1:
		attribute = data[0];
		break;

	default:
		fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
		return -1;
	}

	switch (dv->length) {
	case 2:
		/* data[dv->type] must be zero, from rad_tlv_ok() */
		attrlen = data[dv->type + 1];
		break;

	case 1:
		attrlen = data[dv->type];
		break;

	case 0:
		attrlen = length;
		break;

	default:
		fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
		return -1;
	}

	/*
	 *	See if the VSA is known.
	 */
	da = dict_attrbyvalue(attribute, dv->vendorpec);
	if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
	if (!da) return -1;

	my_len = data2vp(ctx, packet, original, secret, da,
			 data + dv->type + dv->length,
			 attrlen - (dv->type + dv->length),
			 attrlen - (dv->type + dv->length),
			 pvp);
	if (my_len < 0) return my_len;

	return attrlen;
}


/** Convert a fragmented extended attr to a VP
 *
 * Format is:
 *
 * attr
 * length
 * extended-attr
 * flag
 * data...
 *
 * But for the first fragment, we get passed a pointer to the "extended-attr"
 */
static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
				RADIUS_PACKET const *original,
				char const *secret, DICT_ATTR const *da,
				uint8_t const *data,
				size_t attrlen, size_t packetlen,
				VALUE_PAIR **pvp)
{
	ssize_t rcode;
	size_t ext_len;
	bool more;
	uint8_t *head, *tail;
	uint8_t const *attr, *end;
	DICT_ATTR const *child;

	/*
	 *	data = Ext-Attr Flag ...
	 */

	/*
	 *	Not enough room for Ext-Attr + Flag + data, it's a bad
	 *	attribute.
	 */
	if (attrlen < 3) {
	raw:
		/*
		 *	It's not an Extended attribute, it's unknown...
		 */
		child = dict_unknown_afrom_fields(ctx, (da->vendor/ FR_MAX_VENDOR) & 0xff, 0);
		if (!child) {
			fr_strerror_printf("Internal sanity check %d", __LINE__);
			return -1;
		}

		rcode = data2vp(ctx, packet, original, secret, child,
				data, attrlen, attrlen, pvp);
		if (rcode < 0) return rcode;
		return attrlen;
	}

	/*
	 *	No continued data, just decode the attribute in place.
	 */
	if ((data[1] & 0x80) == 0) {
		rcode = data2vp(ctx, packet, original, secret, da,
				data + 2, attrlen - 2, attrlen - 2,
				pvp);

		if ((rcode < 0) || (((size_t) rcode + 2) != attrlen)) goto raw; /* didn't decode all of the data */
		return attrlen;
	}

	/*
	 *	It's continued, but there are no subsequent fragments,
	 *	it's bad.
	 */
	if (attrlen >= packetlen) goto raw;

	/*
	 *	Calculate the length of all of the fragments.  For
	 *	now, they MUST be contiguous in the packet, and they
	 *	MUST be all of the same Type and Ext-Type
	 *
	 *	We skip the first fragment, which doesn't have a
	 *	RADIUS attribute header.
	 */
	ext_len = attrlen - 2;
	attr = data + attrlen;
	end = data + packetlen;

	while (attr < end) {
		/*
		 *	Not enough room for Attr + length + Ext-Attr
		 *	continuation, it's bad.
		 */
		if ((end - attr) < 4) goto raw;

		if (attr[1] < 4) goto raw;

		/*
		 *	If the attribute overflows the packet, it's
		 *	bad.
		 */
		if ((attr + attr[1]) > end) goto raw;

		if (attr[0] != ((da->vendor / FR_MAX_VENDOR) & 0xff)) goto raw; /* not the same Extended-Attribute-X */

		if (attr[2] != data[0]) goto raw; /* Not the same Ext-Attr */

		/*
		 *	Check the continuation flag.
		 */
		more = ((attr[2] & 0x80) != 0);

		/*
		 *	Or, there's no more data, in which case we
		 *	shorten "end" to finish at this attribute.
		 */
		if (!more) end = attr + attr[1];

		/*
		 *	There's more data, but we're at the end of the
		 *	packet.  The attribute is malformed!
		 */
		if (more && ((attr + attr[1]) == end)) goto raw;

		/*
		 *	Add in the length of the data we need to
		 *	concatenate together.
		 */
		ext_len += attr[1] - 4;

		/*
		 *	Go to the next attribute, and stop if there's
		 *	no more.
		 */
		attr += attr[1];
		if (!more) break;
	}

	if (!ext_len) goto raw;

	head = tail = malloc(ext_len);
	if (!head) goto raw;

	/*
	 *	Copy the data over, this time trusting the attribute
	 *	contents.
	 */
	attr = data;
	memcpy(tail, attr + 2, attrlen - 2);
	tail += attrlen - 2;
	attr += attrlen;

	while (attr < end) {
		if (attr[1] > 4) memcpy(tail, attr + 4, attr[1] - 4);
		tail += attr[1] - 4;
		attr += attr[1]; /* skip VID+WiMax header */
	}

	VP_HEXDUMP("long-extended fragments", head, ext_len);

	rcode = data2vp(ctx, packet, original, secret, da,
			head, ext_len, ext_len, pvp);
	free(head);
	if (rcode < 0) goto raw;

	return end - data;
}

/** Convert a Vendor-Specific WIMAX to VPs
 *
 * @note Called ONLY for Vendor-Specific
 */
static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
			     RADIUS_PACKET *packet, RADIUS_PACKET const *original,
			     char const *secret, uint32_t vendor,
			     uint8_t const *data,
			     size_t attrlen, size_t packetlen,
			     VALUE_PAIR **pvp)
{
	ssize_t rcode;
	size_t wimax_len;
	bool more;
	uint8_t *head, *tail;
	uint8_t const *attr, *end;
	DICT_ATTR const *child;

	/*
	 *	data = VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
	 */

	/*
	 *	Not enough room for WiMAX Vendor + Wimax attr + length
	 *	+ continuation, it's a bad attribute.
	 */
	if (attrlen < 8) {
	raw:		
		/*
		 *	It's not a Vendor-Specific, it's unknown...
		 */
		child = dict_unknown_afrom_fields(ctx, PW_VENDOR_SPECIFIC, 0);
		if (!child) {
			fr_strerror_printf("Internal sanity check %d", __LINE__);
			return -1;
		}

		rcode = data2vp(ctx, packet, original, secret, child,
				data, attrlen, attrlen, pvp);
		if (rcode < 0) return rcode;
		return attrlen;
	}

	if (data[5] < 3) goto raw;		/* WiMAX-Length is too small */

	child = dict_attrbyvalue(data[4], vendor);
	if (!child) goto raw;

	/*
	 *	No continued data, just decode the attribute in place.
	 */
	if ((data[6] & 0x80) == 0) {
		if (((size_t) (data[5] + 4)) != attrlen) goto raw; /* WiMAX attribute doesn't fill Vendor-Specific */

		rcode = data2vp(ctx, packet, original, secret, child,
				data + 7, data[5] - 3, data[5] - 3,
				pvp);

		if ((rcode < 0) || (((size_t) rcode + 7) != attrlen)) goto raw; /* didn't decode all of the data */
		return attrlen;
	}

	/*
	 *	Calculate the length of all of the fragments.  For
	 *	now, they MUST be contiguous in the packet, and they
	 *	MUST be all of the same VSA, WiMAX, and WiMAX-attr.
	 *
	 *	The first fragment doesn't have a RADIUS attribute
	 *	header.
	 */
	wimax_len = 0;
	attr = data + 4;
	end = data + packetlen;

	while (attr < end) {
		/*
		 *	Not enough room for Attribute + length +
		 *	continuation, it's bad.
		 */
		if ((end - attr) < 3) goto raw;

		/*
		 *	Must have non-zero data in the attribute.
		 */
		if (attr[1] <= 3) goto raw;

		/*
		 *	If the WiMAX attribute overflows the packet,
		 *	it's bad.
		 */
		if ((attr + attr[1]) > end) goto raw;

		/*
		 *	Check the continuation flag.
		 */
		more = ((attr[2] & 0x80) != 0);

		/*
		 *	Or, there's no more data, in which case we
		 *	shorten "end" to finish at this attribute.
		 */
		if (!more) end = attr + attr[1];

		/*
		 *	There's more data, but we're at the end of the
		 *	packet.  The attribute is malformed!
		 */
		if (more && ((attr + attr[1]) == end)) goto raw;

		/*
		 *	Add in the length of the data we need to
		 *	concatenate together.
		 */
		wimax_len += attr[1] - 3;

		/*
		 *	Go to the next attribute, and stop if there's
		 *	no more.
		 */
		attr += attr[1];
		if (!more) break;

		/*
		 *	data = VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
		 *
		 *	attr = Vendor-Specific VSA-Length VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
		 *
		 */

		/*
		 *	No room for Vendor-Specific + length +
		 *	Vendor(4) + attr + length + continuation + data
		 */
		if ((end - attr) < 9) goto raw;

		if (attr[0] != PW_VENDOR_SPECIFIC) goto raw;
		if (attr[1] < 9) goto raw;
		if ((attr + attr[1]) > end) goto raw;
		if (memcmp(data, attr + 2, 4) != 0) goto raw; /* not WiMAX Vendor ID */

		if (attr[1] != (attr[7] + 6)) goto raw; /* WiMAX attr doesn't exactly fill the VSA */

		if (data[4] != attr[6]) goto raw; /* different WiMAX attribute */

		/*
		 *	Skip over the Vendor-Specific header, and
		 *	continue with the WiMAX attributes.
		 */
		attr += 6;
	}

	/*
	 *	No data in the WiMAX attribute, make a "raw" one.
	 */
	if (!wimax_len) goto raw;

	head = tail = malloc(wimax_len);
	if (!head) return -1;

	/*
	 *	Copy the data over, this time trusting the attribute
	 *	contents.
	 */
	attr = data;
	while (attr < end) {
		memcpy(tail, attr + 4 + 3, attr[4 + 1] - 3);
		tail += attr[4 + 1] - 3;
		attr += 4 + attr[4 + 1]; /* skip VID+WiMax header */
		attr += 2;		 /* skip Vendor-Specific header */
	}

	VP_HEXDUMP("wimax fragments", head, wimax_len);

	rcode = data2vp(ctx, packet, original, secret, child,
			head, wimax_len, wimax_len, pvp);
	free(head);
	if (rcode < 0) goto raw;

	return end - data;
}


/** Convert a top-level VSA to one or more VPs
 *
 */
static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
			    RADIUS_PACKET const *original,
			    char const *secret, uint8_t const *data,
			    size_t attrlen, size_t packetlen,
			    VALUE_PAIR **pvp)
{
	size_t total;
	ssize_t rcode;
	uint32_t vendor;
	DICT_VENDOR *dv;
	VALUE_PAIR *head, **tail;
	DICT_VENDOR my_dv;

	if (attrlen > packetlen) return -1;
	if (attrlen < 5) return -1; /* vid, value */
	if (data[0] != 0) return -1; /* we require 24-bit VIDs */

	VP_TRACE("data2vp_vsas\n");

	memcpy(&vendor, data, 4);
	vendor = ntohl(vendor);
	dv = dict_vendorbyvalue(vendor);
	if (!dv) {
		/*
		 *	RFC format is 1 octet type, 1 octet length
		 */
		if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
			VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
			return -1;
		}

		/*
		 *	It's a known unknown.
		 */
		memset(&my_dv, 0, sizeof(my_dv));
		dv = &my_dv;

		/*
		 *	Fill in the fields.  Note that the name is empty!
		 */
		dv->vendorpec = vendor;
		dv->type = 1;
		dv->length = 1;

		goto create_attrs;
	}

	/*
	 *	WiMAX craziness
	 */
	if (dv->flags) {
		rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
				      data, attrlen, packetlen, pvp);
		return rcode;
	}

	/*
	 *	VSAs should normally be in TLV format.
	 */
	if (rad_tlv_ok(data + 4, attrlen - 4,
		       dv->type, dv->length) < 0) {
		VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
		return -1;
	}

	/*
	 *	There may be more than one VSA in the
	 *	Vendor-Specific.  If so, loop over them all.
	 */
create_attrs:
	data += 4;
	attrlen -= 4;
	packetlen -= 4;
	total = 4;
	head = NULL;
	tail = &head;

	while (attrlen > 0) {
		ssize_t vsa_len;

		vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
				      data, attrlen, tail);
		if (vsa_len < 0) {
			fr_pair_list_free(&head);
			fr_strerror_printf("Internal sanity check %d", __LINE__);
			return -1;
		}

		/*
		 *	Vendors can send zero-length VSAs.
		 */
		if (*tail) tail = &((*tail)->next);

		data += vsa_len;
		attrlen -= vsa_len;
		packetlen -= vsa_len;
		total += vsa_len;
	}

	*pvp = head;
	return total;
}

/** Create any kind of VP from the attribute contents
 *
 * "length" is AT LEAST the length of this attribute, as we
 * expect the caller to have verified the data with
 * rad_packet_ok().  "length" may be up to the length of the
 * packet.
 *
 * @return -1 on error, or "length".
 */
ssize_t data2vp(TALLOC_CTX *ctx,
		RADIUS_PACKET *packet, RADIUS_PACKET const *original,
		char const *secret,
		DICT_ATTR const *da, uint8_t const *start,
		size_t const attrlen, size_t const packetlen,
		VALUE_PAIR **pvp)
{
	int8_t tag = TAG_NONE;
	size_t datalen;
	ssize_t rcode;
	uint32_t vendor;
	DICT_ATTR const *child;
	VALUE_PAIR *vp;
	uint8_t const *data = start;
	char *p;
	uint8_t buffer[256];

	/*
	 *	FIXME: Attrlen can be larger than 253 for extended attrs!
	 */
	if (!da || (attrlen > packetlen) ||
	    ((attrlen > 253) && (attrlen != packetlen)) ||
	    (attrlen > 128*1024)) {
		fr_strerror_printf("data2vp: invalid arguments");
		return -1;
	}

	VP_HEXDUMP("data2vp", start, attrlen);

	VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);

	datalen = attrlen;

	/*
	 *	Hacks for CUI.  The WiMAX spec says that it can be
	 *	zero length, even though this is forbidden by the
	 *	RADIUS specs.  So... we make a special case for it.
	 */
	if (attrlen == 0) {
		if (!((da->vendor == 0) &&
		      (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
			*pvp = NULL;
			return 0;
		}

		/*
		 *	Create a zero-length attribute.
		 */
		vp = fr_pair_afrom_da(ctx, da);
		if (!vp) return -1;
		goto done;
	}

	/*
	 *	Hacks for tags.  If the attribute is capable of
	 *	encoding a tag, and there's room for the tag, and
	 *	there is a tag, or it's encrypted with Tunnel-Password,
	 *	then decode the tag.
	 */
	if (da->flags.has_tag && (datalen > 1) &&
	    ((data[0] < 0x20)
#ifndef WITH_RADIUSV11_ONLY
	     || (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)
#endif
		    )) {

		/*
		 *	Only "short" attributes can be encrypted.
		 */
		if (datalen >= sizeof(buffer)) return -1;

		if (da->type == PW_TYPE_STRING) {
			memcpy(buffer, data + 1, datalen - 1);
			tag = data[0];
			datalen -= 1;

		} else if (da->type == PW_TYPE_INTEGER) {
			memcpy(buffer, data, attrlen);
			tag = buffer[0];
			buffer[0] = 0;

		} else {
			return -1; /* only string and integer can have tags */
		}

		data = buffer;
	}

#ifndef WITH_RADIUSV11_ONLY
	/*
	 *	Decrypt the attribute.
	 */
	if (secret && packet &&

#ifdef WITH_RADIUSV11
	    /*
	     *	RADIUSV11 does not encrypt any attributes.
	     */
	    !packet->radiusv11 &&
#endif

	    (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
		VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
		/*
		 *	Encrypted attributes can only exist for the
		 *	old-style format.  Extended attributes CANNOT
		 *	be encrypted.
		 */
		if (attrlen > 253) {
			return -1;
		}

		if (data == start) {
			memcpy(buffer, data, attrlen);
		}
		data = buffer;

		switch (da->flags.encrypt) { /* can't be tagged */
		/*
		 *  User-Password
		 */
		case FLAG_ENCRYPT_USER_PASSWORD:
			if (original) {
				rad_pwdecode((char *) buffer,
					     attrlen, secret,
					     original->vector);
			} else {
				rad_pwdecode((char *) buffer,
					     attrlen, secret,
					     packet->vector);
			}
			buffer[253] = '\0';

			/*
			 *	MS-CHAP-MPPE-Keys are 24 octets, and
			 *	encrypted.  Since it's binary, we can't
			 *	look for trailing zeros.
			 */
			if (da->flags.length) {
				if (datalen > da->flags.length) {
					datalen = da->flags.length;
				} /* else leave datalen alone */
			} else {
				/*
				 *	Take off trailing zeros from the END.
				 *	This allows passwords to have zeros in
				 *	the middle of a field.
				 *
				 *	However, if the password has a zero at
				 *	the end, it will get mashed by this
				 *	code.  There's really no way around
				 *	that.
				 */
				while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
			}
			break;

		/*
		 *	Tunnel-Password's may go ONLY in response
		 *	packets.  They can have a tag, so datalen is
		 *	not the same as attrlen.
		 */
		case FLAG_ENCRYPT_TUNNEL_PASSWORD:
			if (rad_tunnel_pwdecode(buffer, &datalen, secret,
						original ? original->vector : nullvector) < 0) {
				goto raw;
			}
			break;

		/*
		 *  Ascend-Send-Secret
		 *  Ascend-Receive-Secret
		 */
		case FLAG_ENCRYPT_ASCEND_SECRET:
			if (!original) {
				goto raw;
			} else {
				uint8_t my_digest[AUTH_VECTOR_LEN];
				size_t secret_len;

				secret_len = datalen;
				if (secret_len > AUTH_VECTOR_LEN) secret_len = AUTH_VECTOR_LEN;

				make_secret(my_digest,
					    original->vector,
					    secret, data, secret_len);
				memcpy(buffer, my_digest,
				       AUTH_VECTOR_LEN );
				buffer[AUTH_VECTOR_LEN] = '\0';
				datalen = strlen((char *) buffer);
			}
			break;

		default:
			break;
		} /* switch over encryption flags */
	}
#endif	/* WITH_RADIUSV11_ONLY */

	/*
	 *	Double-check the length after decrypting the
	 *	attribute.
	 */
	VP_TRACE("data2vp: type %u\n", da->type);
	switch (da->type) {
	case PW_TYPE_STRING:
	case PW_TYPE_OCTETS:
		break;

	case PW_TYPE_ABINARY:
		if (datalen > sizeof(vp->vp_filter)) goto raw;
		break;

	case PW_TYPE_INTEGER:
	case PW_TYPE_IPV4_ADDR:
	case PW_TYPE_DATE:
	case PW_TYPE_SIGNED:
		if (datalen != 4) goto raw;
		break;

	case PW_TYPE_INTEGER64:
	case PW_TYPE_IFID:
		if (datalen != 8) goto raw;
		break;

	case PW_TYPE_IPV6_ADDR:
		if (datalen != 16) goto raw;
		break;

	case PW_TYPE_IPV6_PREFIX:
		if ((datalen < 2) || (datalen > 18)) goto raw;
		if (data[1] > 128) goto raw;
		break;

	case PW_TYPE_BYTE:
		if (datalen != 1) goto raw;
		break;

	case PW_TYPE_SHORT:
		if (datalen != 2) goto raw;
		break;

	case PW_TYPE_ETHERNET:
		if (datalen != 6) goto raw;
		break;

	case PW_TYPE_COMBO_IP_ADDR:
		if (datalen == 4) {
			child = dict_attrbytype(da->attr, da->vendor,
						PW_TYPE_IPV4_ADDR);
		} else if (datalen == 16) {
			child = dict_attrbytype(da->attr, da->vendor,
					     PW_TYPE_IPV6_ADDR);
		} else {
			goto raw;
		}
		if (!child) goto raw;
		da = child;	/* re-write it */
		break;

	case PW_TYPE_IPV4_PREFIX:
		if (datalen != 6) goto raw;
		if ((data[1] & 0x3f) > 32) goto raw;
		break;

		/*
		 *	The rest of the data types can cause
		 *	recursion!  Ask yourself, "is recursion OK?"
		 */

	case PW_TYPE_EXTENDED:
		if (datalen < 2) goto raw; /* etype, value */

		child = dict_attrbyparent(da, data[0], 0);
		if (!child) goto raw;

		/*
		 *	Recurse to decode the contents, which could be
		 *	a TLV, IPaddr, etc.  Note that we decode only
		 *	the current attribute, and we ignore any extra
		 *	data after it.
		 */
		rcode = data2vp(ctx, packet, original, secret, child,
				data + 1, attrlen - 1, attrlen - 1, pvp);
		if (rcode < 0) goto raw;
		return 1 + rcode;

	case PW_TYPE_LONG_EXTENDED:
		if (datalen < 3) goto raw; /* etype, flags, value */

		child = dict_attrbyparent(da, data[0], 0);
		if (!child) {
			if ((data[0] != PW_VENDOR_SPECIFIC) ||
			    (datalen < (3 + 4 + 1))) {
				/* da->attr < 255, da->vendor == 0 */
				child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
			} else {
				/*
				 *	Try to find the VSA.
				 */
				memcpy(&vendor, data + 3, 4);
				vendor = ntohl(vendor);

				if (vendor == 0) goto raw;

				child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
			}

			if (!child) {
				fr_strerror_printf("Internal sanity check %d", __LINE__);
				return -1;
			}
		}

		/*
		 *	This requires a whole lot more work.
		 */
		return data2vp_extended(ctx, packet, original, secret, child,
					start, attrlen, packetlen, pvp);

	case PW_TYPE_EVS:
		if (datalen < 6) goto raw; /* vid, vtype, value */

		if (data[0] != 0) goto raw; /* we require 24-bit VIDs */

		memcpy(&vendor, data, 4);
		vendor = ntohl(vendor);
		vendor |= da->vendor;

		child = dict_attrbyvalue(data[4], vendor);
		if (!child) {
			/*
			 *	Create a "raw" attribute from the
			 *	contents of the EVS VSA.
			 */
			da = dict_unknown_afrom_fields(ctx, data[4], vendor);
			data += 5;
			datalen -= 5;
			break;
		}

		rcode = data2vp(ctx, packet, original, secret, child,
				data + 5, attrlen - 5, attrlen - 5, pvp);
		if (rcode < 0) goto raw;
		return 5 + rcode;

	case PW_TYPE_TLV:
		/*
		 *	We presume that the TLVs all fit into one
		 *	attribute, OR they've already been grouped
		 *	into a contiguous memory buffer.
		 */
		rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
					 data, attrlen, pvp);
		if (rcode < 0) goto raw;
		return rcode;

	case PW_TYPE_VSA:
		/*
		 *	VSAs can be WiMAX, in which case they don't
		 *	fit into one attribute.
		 */
		rcode = data2vp_vsas(ctx, packet, original, secret,
				     data, attrlen, packetlen, pvp);
		if (rcode < 0) goto raw;
		return rcode;

	default:
	raw:
		/*
		 *	If it's already unknown, don't create a new
		 *	unknown one.
		 */
		if (da->flags.is_unknown) break;

		/*
		 *	Re-write the attribute to be "raw".  It is
		 *	therefore of type "octets", and will be
		 *	handled below.
		 *
		 *      We allocate the VP *first*, and then the da
		 *      from it, so that there are no memory leaks.
		 */
		vp = fr_pair_alloc(ctx);
		if (!vp) return -1;

		da = dict_unknown_afrom_fields(vp, da->attr, da->vendor);
		if (!da) {
			fr_strerror_printf("Internal sanity check %d", __LINE__);
			return -1;
		}
		tag = TAG_NONE;
		vp->da = da;
		goto alloc_raw;
	}

	/*
	 *	And now that we've verified the basic type
	 *	information, decode the actual data.
	 */
	vp = fr_pair_afrom_da(ctx, da);
	if (!vp) return -1;

alloc_raw:
	vp->vp_length = datalen;
	vp->tag = tag;

	switch (da->type) {
	case PW_TYPE_STRING:
		p = talloc_array(vp, char, vp->vp_length + 1);
#ifdef __clang_analyzer__
		if (!p) goto fail;
#endif
		memcpy(p, data, vp->vp_length);
		p[vp->vp_length] = '\0';
		vp->vp_strvalue = p;
		break;

	case PW_TYPE_OCTETS:
		fr_pair_value_memcpy(vp, data, vp->vp_length);
		break;

	case PW_TYPE_ABINARY:
		if (vp->vp_length > sizeof(vp->vp_filter)) {
			vp->vp_length = sizeof(vp->vp_filter);
		}
		memcpy(vp->vp_filter, data, vp->vp_length);
		break;

	case PW_TYPE_BYTE:
		vp->vp_byte = data[0];
		break;

	case PW_TYPE_SHORT:
		vp->vp_short = (data[0] << 8) | data[1];
		break;

	case PW_TYPE_INTEGER:
		memcpy(&vp->vp_integer, data, 4);
		vp->vp_integer = ntohl(vp->vp_integer);
		break;

	case PW_TYPE_INTEGER64:
		memcpy(&vp->vp_integer64, data, 8);
		vp->vp_integer64 = ntohll(vp->vp_integer64);
		break;

	case PW_TYPE_DATE:
		memcpy(&vp->vp_date, data, 4);
		vp->vp_date = ntohl(vp->vp_date);
		break;

	case PW_TYPE_ETHERNET:
		memcpy(vp->vp_ether, data, 6);
		break;

	case PW_TYPE_IPV4_ADDR:
		memcpy(&vp->vp_ipaddr, data, 4);
		break;

	case PW_TYPE_IFID:
		memcpy(vp->vp_ifid, data, 8);
		break;

	case PW_TYPE_IPV6_ADDR:
		memcpy(&vp->vp_ipv6addr, data, 16);
		break;

	case PW_TYPE_IPV6_PREFIX:
		/*
		 *	FIXME: double-check that
		 *	(vp->vp_octets[1] >> 3) matches vp->vp_length + 2
		 */
		memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
		if (vp->vp_length < 18) {
			memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
			       18 - vp->vp_length);
		}
		break;

	case PW_TYPE_IPV4_PREFIX:
		/* FIXME: do the same double-check as for IPv6Prefix */
		memcpy(vp->vp_ipv4prefix, data, vp->vp_length);

		/*
		 *	/32 means "keep all bits".  Otherwise, mask
		 *	them out.
		 */
		if ((data[1] & 0x3f) > 32) {
			uint32_t addr, mask;

			memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
			mask = 1;
			mask <<= (32 - (data[1] & 0x3f));
			mask--;
			mask = ~mask;
			mask = htonl(mask);
			addr &= mask;
			memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
		}
		break;

	case PW_TYPE_SIGNED:	/* overloaded with vp_integer */
		memcpy(&vp->vp_integer, data, 4);
		vp->vp_integer = ntohl(vp->vp_integer);
		break;

#ifdef __clang_analyzer__
	fail:
#endif
	default:
		fr_pair_list_free(&vp);
		fr_strerror_printf("Internal sanity check %d", __LINE__);
		return -1;
	}

done:
	vp->type = VT_DATA;
	*pvp = vp;

	return attrlen;
}


/** Create a "normal" VALUE_PAIR from the given data
 *
 */
ssize_t rad_attr2vp(TALLOC_CTX *ctx,
		    RADIUS_PACKET *packet, RADIUS_PACKET const *original,
		    char const *secret,
		    uint8_t const *data, size_t length,
		    VALUE_PAIR **pvp)
{
	ssize_t rcode;

	DICT_ATTR const *da;

	if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
		fr_strerror_printf("rad_attr2vp: Insufficient data");
		return -1;
	}

	da = dict_attrbyvalue(data[0], 0);
	if (!da) {
		VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
		da = dict_unknown_afrom_fields(ctx, data[0], 0);
	}
	if (!da) return -1;

	/*
	 *	Pass the entire thing to the decoding function
	 */
	if (da->flags.concat) {
		VP_TRACE("attr2vp: concat attribute\n");
		return data2vp_concat(ctx, da, data, length, pvp);
	}

	if (!da->vendor && (da->attr == PW_NAS_FILTER_RULE)) {
		VP_TRACE("attr2vp: NAS-Filter-Rule attribute\n");
		return data2vp_nas_filter_rule(ctx, da, data, length, pvp);
	}

	/*
	 *	Note that we pass the entire length, not just the
	 *	length of this attribute.  The Extended or WiMAX
	 *	attributes may have the "continuation" bit set, and
	 *	will thus be more than one attribute in length.
	 */
	rcode = data2vp(ctx, packet, original, secret, da,
			data + 2, data[1] - 2, length - 2, pvp);
	if (rcode < 0) return rcode;

	return 2 + rcode;
}

fr_thread_local_setup(uint8_t *, rad_vp2data_buff)

/** Converts vp_data to network byte order
 *
 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
 * in an architecture independent format.
 *
 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
 * as the source VALUE_PAIR is not freed.
 *
 * @param out where to write the pointer to the value.
 * @param vp to get the value from.
 * @return -1 on error, or the length of the value
 */
ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
{
	uint8_t		*buffer;
	uint32_t	lvalue;
	uint64_t	lvalue64;

	*out = NULL;

	buffer = fr_thread_local_init(rad_vp2data_buff, free);
	if (!buffer) {
		int ret;

		buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
		if (!buffer) {
			fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
			return -1;
		}

		ret = fr_thread_local_set(rad_vp2data_buff, buffer);
		if (ret != 0) {
			fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
			free(buffer);
			return -1;
		}
	}

	VERIFY_VP(vp);

	switch (vp->da->type) {
	case PW_TYPE_STRING:
	case PW_TYPE_OCTETS:
		memcpy(out, &vp->data.ptr, sizeof(*out));
		break;

	/*
	 *	All of these values are at the same location.
	 */
	case PW_TYPE_IFID:
	case PW_TYPE_IPV4_ADDR:
	case PW_TYPE_IPV6_ADDR:
	case PW_TYPE_IPV6_PREFIX:
	case PW_TYPE_IPV4_PREFIX:
	case PW_TYPE_ABINARY:
	case PW_TYPE_ETHERNET:
	case PW_TYPE_COMBO_IP_ADDR:
	case PW_TYPE_COMBO_IP_PREFIX:
	{
		void const *p = &vp->data;
		memcpy(out, &p, sizeof(*out));
		break;
	}

	case PW_TYPE_BOOLEAN:
		buffer[0] = vp->vp_byte & 0x01;
		*out = buffer;
		break;

	case PW_TYPE_BYTE:
		buffer[0] = vp->vp_byte & 0xff;
		*out = buffer;
		break;

	case PW_TYPE_SHORT:
		buffer[0] = (vp->vp_short >> 8) & 0xff;
		buffer[1] = vp->vp_short & 0xff;
		*out = buffer;
		break;

	case PW_TYPE_INTEGER:
		lvalue = htonl(vp->vp_integer);
		memcpy(buffer, &lvalue, sizeof(lvalue));
		*out = buffer;
		break;

	case PW_TYPE_INTEGER64:
		lvalue64 = htonll(vp->vp_integer64);
		memcpy(buffer, &lvalue64, sizeof(lvalue64));
		*out = buffer;
		break;

	case PW_TYPE_DATE:
		lvalue = htonl(vp->vp_date);
		memcpy(buffer, &lvalue, sizeof(lvalue));
		*out = buffer;
		break;

	case PW_TYPE_SIGNED:
	{
		int32_t slvalue = htonl(vp->vp_signed);
		memcpy(buffer, &slvalue, sizeof(slvalue));
		*out = buffer;
		break;
	}

	case PW_TYPE_INVALID:
	case PW_TYPE_EXTENDED:
	case PW_TYPE_LONG_EXTENDED:
	case PW_TYPE_EVS:
	case PW_TYPE_VSA:
	case PW_TYPE_TLV:
	case PW_TYPE_TIMEVAL:
	case PW_TYPE_MAX:
		fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
		return -1;

	/* Don't add default */
	}

	return vp->vp_length;
}

/** Calculate/check digest, and decode radius attributes
 *
 * @return -1 on decoding error, 0 on success
 */
int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
	       char const *secret)
{
	int			packet_length;
	uint32_t		num_attributes;
	uint8_t			*ptr;
	radius_packet_t		*hdr;
	VALUE_PAIR *head, **tail, *vp = NULL;

	/*
	 *	Extract attribute-value pairs
	 */
	hdr = (radius_packet_t *)packet->data;
	ptr = hdr->data;
	packet_length = packet->data_len - RADIUS_HDR_LEN;

	head = NULL;
	tail = &head;
	num_attributes = 0;

	/*
	 *	Loop over the attributes, decoding them into VPs.
	 */
	while (packet_length > 0) {
		ssize_t my_len;

#ifdef WITH_RADIUSV11
		/*
		 *	Don't decode Message-Authenticator
		 */
		if (ptr[0] == PW_MESSAGE_AUTHENTICATOR) {
			packet_length -= ptr[1];
			ptr += ptr[1];
			continue;
		}

		/*
		 *	Don't decode Original-Packet-Code
		 */
		if ((ptr[0] == PW_EXTENDED_ATTRIBUTE_1) && (ptr[1] >= 3) && (ptr[2] == 4)) {
			packet_length -= ptr[1];
			ptr += ptr[1];
			continue;
		}
#endif

		/*
		 *	This may return many VPs
		 */
		my_len = rad_attr2vp(packet, packet, original, secret,
				     ptr, packet_length, &vp);
		if (my_len < 0) {
			fr_pair_list_free(&head);
			return -1;
		}

		*tail = vp;
		while (vp) {
			num_attributes++;
			tail = &(vp->next);
			vp = vp->next;
		}

		/*
		 *	VSA's may not have been counted properly in
		 *	rad_packet_ok() above, as it is hard to count
		 *	then without using the dictionary.  We
		 *	therefore enforce the limits here, too.
		 */
		if ((fr_max_attributes > 0) &&
		    (num_attributes > fr_max_attributes)) {
			char host_ipaddr[128];

			fr_pair_list_free(&head);
			fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
				   inet_ntop(packet->src_ipaddr.af,
					     &packet->src_ipaddr.ipaddr,
					     host_ipaddr, sizeof(host_ipaddr)),
				   num_attributes, fr_max_attributes);
			return -1;
		}

		ptr += my_len;
		packet_length -= my_len;
	}

	/*
	 *	Merge information from the outside world into our
	 *	random pool.
	 */
	fr_rand_seed(packet->data, RADIUS_HDR_LEN);

	/*
	 *	There may be VP's already in the packet.  Don't
	 *	destroy them.  Instead, add the decoded attributes to
	 *	the tail of the list.
	 */
	for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
		/* nothing */
	}
	*tail = head;

	return 0;
}

#ifndef WITH_RADIUSV11_ONLY
/** Encode password
 *
 * We assume that the passwd buffer passed is big enough.
 * RFC2138 says the password is max 128 chars, so the size
 * of the passwd buffer must be at least 129 characters.
 * Preferably it's just MAX_STRING_LEN.
 *
 * int *pwlen is updated to the new length of the encrypted
 * password - a multiple of 16 bytes.
 */
int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
		 uint8_t const *vector)
{
	FR_MD5_CTX context, old;
	uint8_t	digest[AUTH_VECTOR_LEN];
	int	i, n, secretlen;
	int	len;

	/*
	 *	RFC maximum is 128 bytes.
	 *
	 *	If length is zero, pad it out with zeros.
	 *
	 *	If the length isn't aligned to 16 bytes,
	 *	zero out the extra data.
	 */
	len = *pwlen;

	if (len > 128) len = 128;

	if (len == 0) {
		memset(passwd, 0, AUTH_PASS_LEN);
		len = AUTH_PASS_LEN;
	} else if ((len % AUTH_PASS_LEN) != 0) {
		memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
		len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
	}
	*pwlen = len;

	/*
	 *	Use the secret to setup the decryption digest
	 */
	secretlen = strlen(secret);

	fr_md5_init(&context);
	fr_md5_init(&old);
	fr_md5_update(&context, (uint8_t const *) secret, secretlen);
	fr_md5_copy(old, context);		/* save intermediate work */

	/*
	 *	Encrypt it in place.  Don't bother checking
	 *	len, as we've ensured above that it's OK.
	 */
	for (n = 0; n < len; n += AUTH_PASS_LEN) {
		if (n == 0) {
			fr_md5_update(&context, vector, AUTH_PASS_LEN);
			fr_md5_final(digest, &context);
		} else {
			fr_md5_copy(context, old);
			fr_md5_update(&context,
				     (uint8_t *) passwd + n - AUTH_PASS_LEN,
				     AUTH_PASS_LEN);
			fr_md5_final(digest, &context);
		}

		for (i = 0; i < AUTH_PASS_LEN; i++) {
			passwd[i + n] ^= digest[i];
		}
	}

	fr_md5_destroy(&old);
	fr_md5_destroy(&context);

	return 0;
}

/** Decode password
 *
 */
int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
		 uint8_t const *vector)
{
	FR_MD5_CTX context, old;
	uint8_t	digest[AUTH_VECTOR_LEN];
	int	i;
	size_t	n, secretlen;

	/*
	 *	The RFC's say that the maximum is 128.
	 *	The buffer we're putting it into above is 254, so
	 *	we don't need to do any length checking.
	 */
	if (pwlen > 128) pwlen = 128;

	/*
	 *	Catch idiots.
	 */
	if (pwlen == 0) goto done;

	/*
	 *	Use the secret to setup the decryption digest
	 */
	secretlen = strlen(secret);

	fr_md5_init(&context);
	fr_md5_init(&old);
	fr_md5_update(&context, (uint8_t const *) secret, secretlen);
	fr_md5_copy(old, context);		/* save intermediate work */

	/*
	 *	The inverse of the code above.
	 */
	for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
		if (n == 0) {
			fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
			fr_md5_final(digest, &context);

			fr_md5_copy(context, old);
			if (pwlen > AUTH_PASS_LEN) {
				fr_md5_update(&context, (uint8_t *) passwd,
					     AUTH_PASS_LEN);
			}
		} else {
			fr_md5_final(digest, &context);

			fr_md5_copy(context, old);
			if (pwlen > (n + AUTH_PASS_LEN)) {
				fr_md5_update(&context, (uint8_t *) passwd + n,
					     AUTH_PASS_LEN);
			}
		}

		for (i = 0; i < AUTH_PASS_LEN; i++) {
			passwd[i + n] ^= digest[i];
		}
	}

 done:
	fr_md5_destroy(&old);
	fr_md5_destroy(&context);

	passwd[pwlen] = '\0';
	return strlen(passwd);
}


/** Encode Tunnel-Password attributes when sending them out on the wire
 *
 * int *pwlen is updated to the new length of the encrypted
 * password - a multiple of 16 bytes.
 *
 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
 * value MD5 hash.
 */
ssize_t rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
{
	uint8_t	buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
	unsigned char	digest[AUTH_VECTOR_LEN];
	char*   salt;
	int	i, n, secretlen;
	unsigned len, n2;

	len = *pwlen;

	if (len > 127) len = 127;

	/*
	 *	Shift the password 3 positions right to place a salt and original
	 *	length, tag will be added automatically on packet send.
	 */
	for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
	salt = passwd;
	passwd += 2;

	/*
	 *	save original password length as first password character;
	 */
	*passwd = len;
	len += 1;


	/*
	 *	Generate salt.  The RFC's say:
	 *
	 *	The high bit of salt[0] must be set, each salt in a
	 *	packet should be unique, and they should be random
	 *
	 *	So, we set the high bit, add in a counter, and then
	 *	add in some CSPRNG data.  should be OK..
	 */
	salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
		   (fr_rand() & 0x07));
	salt[1] = fr_rand();

	/*
	 *	Padd password to multiple of AUTH_PASS_LEN bytes.
	 */
	n = len % AUTH_PASS_LEN;
	if (n) {
		n = AUTH_PASS_LEN - n;
		for (; n > 0; n--, len++)
			passwd[len] = 0;
	}
	/* set new password length */
	*pwlen = len + 2;

	/*
	 *	Use the secret to setup the decryption digest
	 */
	secretlen = strlen(secret);
	memcpy(buffer, secret, secretlen);

	for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
		if (!n2) {
			memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
			memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
			fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
		} else {
			memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
			fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
		}

		for (i = 0; i < AUTH_PASS_LEN; i++) {
			passwd[i + n2] ^= digest[i];
		}
	}
	passwd[n2] = 0;
	return 0;
}

/** Decode Tunnel-Password encrypted attributes
 *
 * Defined in RFC-2868, this uses a two char SALT along with the
 * initial intermediate value, to differentiate it from the
 * above.
 */
ssize_t rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
{
	FR_MD5_CTX  context, old;
	uint8_t		digest[AUTH_VECTOR_LEN];
	int		secretlen;
	size_t		i, n, encrypted_len, reallen;

	encrypted_len = *pwlen;

	/*
	 *	We need at least a salt.
	 */
	if (encrypted_len < 2) {
		fr_strerror_printf("tunnel password is too short");
		return -1;
	}

	/*
	 *	There's a salt, but no password.  Or, there's a salt
	 *	and a 'data_len' octet.  It's wrong, but at least we
	 *	can figure out what it means: the password is empty.
	 *
	 *	Note that this means we ignore the 'data_len' field,
	 *	if the attribute length tells us that there's no
	 *	more data.  So the 'data_len' field may be wrong,
	 *	but that's ok...
	 */
	if (encrypted_len <= 3) {
		passwd[0] = 0;
		*pwlen = 0;
		return 0;
	}

	encrypted_len -= 2;		/* discount the salt */

	/*
	 *	Use the secret to setup the decryption digest
	 */
	secretlen = strlen(secret);

	fr_md5_init(&context);
	fr_md5_init(&old);
	fr_md5_update(&context, (uint8_t const *) secret, secretlen);
	fr_md5_copy(old, context);		/* save intermediate work */

	/*
	 *	Set up the initial key:
	 *
	 *	 b(1) = MD5(secret + vector + salt)
	 */
	fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
	fr_md5_update(&context, passwd, 2);

	reallen = 0;
	for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
		size_t base;
		size_t block_len = AUTH_PASS_LEN;

		/*
		 *	Ensure we don't overflow the input on MD5
		 */
		if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
			block_len = *pwlen - n - 2;
		}

		if (n == 0) {
			base = 1;

			fr_md5_final(digest, &context);

			fr_md5_copy(context, old);

			/*
			 *	A quick check: decrypt the first octet
			 *	of the password, which is the
			 *	'data_len' field.  Ensure it's sane.
			 */
			reallen = passwd[2] ^ digest[0];
			if (reallen > encrypted_len) {
				fr_strerror_printf("tunnel password is too long for the attribute");
				return -1;
			}

			fr_md5_update(&context, passwd + 2, block_len);

		} else {
			base = 0;

			fr_md5_final(digest, &context);

			fr_md5_copy(context, old);
			fr_md5_update(&context, passwd + n + 2, block_len);
		}

		for (i = base; i < block_len; i++) {
			passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
		}
	}

	*pwlen = reallen;
	passwd[reallen] = 0;

	fr_md5_destroy(&old);
	fr_md5_destroy(&context);

	return reallen;
}

/** Encode a CHAP password
 *
 * @bug FIXME: might not work with Ascend because
 * we use vp->vp_length, and Ascend gear likes
 * to send an extra '\0' in the string!
 */
int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
		    VALUE_PAIR *password)
{
	int		i;
	uint8_t		*ptr;
	uint8_t		string[MAX_STRING_LEN * 2 + 1];
	VALUE_PAIR	*challenge;

	/*
	 *	Sanity check the input parameters
	 */
	if ((packet == NULL) || (password == NULL)) {
		return -1;
	}

	/*
	 *	Note that the password VP can be EITHER
	 *	a User-Password attribute (from a check-item list),
	 *	or a CHAP-Password attribute (the client asking
	 *	the library to encode it).
	 */

	i = 0;
	ptr = string;
	*ptr++ = id;

	i++;
	memcpy(ptr, password->vp_strvalue, password->vp_length);
	ptr += password->vp_length;
	i += password->vp_length;

	/*
	 *	Use Chap-Challenge pair if present,
	 *	Request Authenticator otherwise.
	 */
	challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
	if (challenge) {
		memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
		i += challenge->vp_length;
	} else {
		memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
		i += AUTH_VECTOR_LEN;
	}

	*output = id;
	fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);

	return 0;
}
#endif	/* WITH_RADIUSV11_ONLYx */


/** Seed the random number generator
 *
 * May be called any number of times.
 */
void fr_rand_seed(void const *data, size_t size)
{
	uint32_t hash;

	/*
	 *	Ensure that the pool is initialized.
	 */
	if (!fr_rand_initialized) {
		int fd;

		memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));

		fd = open("/dev/urandom", O_RDONLY);
		if (fd >= 0) {
			size_t total;
			ssize_t this;

			total = 0;
			while (total < sizeof(fr_rand_pool.randrsl)) {
				this = read(fd, fr_rand_pool.randrsl,
					    sizeof(fr_rand_pool.randrsl) - total);
				if ((this < 0) && (errno != EINTR)) break;
				if (this > 0) total += this;
			}
			close(fd);
		} else {
			fr_rand_pool.randrsl[0] = fd;
			fr_rand_pool.randrsl[1] = time(NULL);
			fr_rand_pool.randrsl[2] = errno;
		}

		fr_randinit(&fr_rand_pool, 1);
		fr_rand_pool.randcnt = 0;
		fr_rand_initialized = 1;
	}

	if (!data) return;

	/*
	 *	Hash the user data
	 */
	hash = fr_rand();
	if (!hash) hash = fr_rand();
	hash = fr_hash_update(data, size, hash);

	fr_rand_pool.randmem[fr_rand_pool.randcnt & 0xff] ^= hash;
}


/** Return a 32-bit random number
 *
 */
uint32_t fr_rand(void)
{
	uint32_t num;

	/*
	 *	Ensure that the pool is initialized.
	 */
	if (!fr_rand_initialized) {
		fr_rand_seed(NULL, 0);
	}

	num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++ & 0xff];
	if (fr_rand_pool.randcnt >= 256) {
		fr_rand_pool.randcnt = 0;
		fr_isaac(&fr_rand_pool);
	}

	return num;
}


/** Allocate a new RADIUS_PACKET
 *
 * @param ctx the context in which the packet is allocated. May be NULL if
 *	the packet is not associated with a REQUEST.
 * @param new_vector if true a new request authenticator will be generated.
 * @return a new RADIUS_PACKET or NULL on error.
 */
RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
{
	RADIUS_PACKET	*rp;

	rp = talloc_zero(ctx, RADIUS_PACKET);
	if (!rp) {
		fr_strerror_printf("out of memory");
		return NULL;
	}
	rp->id = -1;
	rp->offset = -1;

	if (new_vector) {
		int i;
		uint32_t hash, base;

		/*
		 *	Don't expose the actual contents of the random
		 *	pool.
		 */
		base = fr_rand();
		for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
			hash = fr_rand() ^ base;
			memcpy(rp->vector + i, &hash, sizeof(hash));
		}
	}
	fr_rand();		/* stir the pool again */

	return rp;
}

/** Allocate a new RADIUS_PACKET response
 *
 * @param ctx the context in which the packet is allocated. May be NULL if
 *	the packet is not associated with a REQUEST.
 * @param packet The request packet.
 * @return a new RADIUS_PACKET or NULL on error.
 */
RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
{
	RADIUS_PACKET *reply;

	if (!packet) return NULL;

	reply = rad_alloc(ctx, false);
	if (!reply) return NULL;

	/*
	 *	Initialize the fields from the request.
	 */
	reply->sockfd = packet->sockfd;
	reply->dst_ipaddr = packet->src_ipaddr;
	reply->src_ipaddr = packet->dst_ipaddr;
	reply->dst_port = packet->src_port;
	reply->src_port = packet->dst_port;
	reply->id = packet->id;
	reply->code = 0; /* UNKNOWN code */
	memcpy(reply->vector, packet->vector,
	       sizeof(reply->vector));
	reply->vps = NULL;
	reply->data = NULL;
	reply->data_len = 0;

#ifdef WITH_TCP
	reply->proto = packet->proto;
#ifdef WITH_RADIUSV11
	reply->radiusv11 = packet->radiusv11;
#endif
#endif
	return reply;
}


/** Free a RADIUS_PACKET
 *
 */
void rad_free(RADIUS_PACKET **radius_packet_ptr)
{
	RADIUS_PACKET *radius_packet;

	if (!radius_packet_ptr || !*radius_packet_ptr) return;
	radius_packet = *radius_packet_ptr;

	VERIFY_PACKET(radius_packet);

	fr_pair_list_free(&radius_packet->vps);

	talloc_free(radius_packet);
	*radius_packet_ptr = NULL;
}

/** Duplicate a RADIUS_PACKET
 *
 * @param ctx the context in which the packet is allocated. May be NULL if
 *	the packet is not associated with a REQUEST.
 * @param in The packet to copy
 * @return a new RADIUS_PACKET or NULL on error.
 */
RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
{
	RADIUS_PACKET *out;

	out = rad_alloc(ctx, false);
	if (!out) return NULL;

	/*
	 *	Bootstrap by copying everything.
	 */
	memcpy(out, in, sizeof(*out));

	/*
	 *	Then reset necessary fields
	 */
	out->sockfd = -1;

	out->data = NULL;
	out->data_len = 0;

	out->vps = fr_pair_list_copy(out, in->vps);
	out->offset = 0;

	return out;
}

#ifdef WITH_RADIUSV11
const FR_NAME_NUMBER radiusv11_types[] = {
	{ "forbid",	FR_RADIUSV11_FORBID },
	{ "allow",	FR_RADIUSV11_ALLOW },
	{ "require",	FR_RADIUSV11_REQUIRE },
	{ NULL, 0 }

};
#endif