aboutsummaryrefslogtreecommitdiff
path: root/srtp/srtp.c
blob: 3cc026a2cbd0632ed79b12160a632667f3615290 (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
/*
 * srtp.c
 *
 * the secure real-time transport protocol
 *
 * David A. McGrew
 * Cisco Systems, Inc.
 */
/*
 *	
 * Copyright (c) 2001-2017, Cisco Systems, Inc.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 *   Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 *   Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the following
 *   disclaimer in the documentation and/or other materials provided
 *   with the distribution.
 * 
 *   Neither the name of the Cisco Systems, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "srtp.h"
#include "srtp_priv.h"
#include "crypto_types.h"
#include "err.h"
#include "ekt.h"             /* for SRTP Encrypted Key Transport */
#include "alloc.h"           /* for srtp_crypto_alloc()          */
#ifdef OPENSSL
#include "aes_gcm_ossl.h"    /* for AES GCM mode  */
# ifdef OPENSSL_KDF
# include <openssl/kdf.h>
# include "aes_icm_ossl.h"    /* for AES GCM mode  */
# endif
#endif

#include <limits.h>
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#elif defined(HAVE_WINSOCK2_H)
# include <winsock2.h>
#endif


/* the debug module for srtp */

srtp_debug_module_t mod_srtp = {
  0,                  /* debugging is off by default */
  "srtp"              /* printable name for module   */
};

#define octets_in_rtp_header   12
#define uint32s_in_rtp_header  3
#define octets_in_rtcp_header  8
#define uint32s_in_rtcp_header 2
#define octets_in_rtp_extn_hdr 4

static srtp_err_status_t
srtp_validate_rtp_header(void *rtp_hdr, int *pkt_octet_len) {
  if (*pkt_octet_len < octets_in_rtp_header)
    return srtp_err_status_bad_param;

  srtp_hdr_t *hdr = (srtp_hdr_t *)rtp_hdr;

  /* Check RTP header length */
  int rtp_header_len = octets_in_rtp_header + 4 * hdr->cc;
  if (hdr->x == 1)
    rtp_header_len += octets_in_rtp_extn_hdr;

  if (*pkt_octet_len < rtp_header_len)
    return srtp_err_status_bad_param;

  /* Verifing profile length. */
  if (hdr->x == 1) {
    srtp_hdr_xtnd_t *xtn_hdr =
      (srtp_hdr_xtnd_t *)((uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc);
    int profile_len = ntohs(xtn_hdr->length);
    rtp_header_len += profile_len * 4;
    /* profile length counts the number of 32-bit words */
    if (*pkt_octet_len < rtp_header_len)
      return srtp_err_status_bad_param;
  }
  return srtp_err_status_ok;
}

const char *srtp_get_version_string ()
{
    /*
     * Simply return the autotools generated string
     */
    return SRTP_VER_STRING;
}

unsigned int srtp_get_version ()
{
    unsigned int major = 0, minor = 0, micro = 0;
    unsigned int rv = 0;
    int parse_rv;

    /*
     * Parse the autotools generated version 
     */
    parse_rv = sscanf(SRTP_VERSION, "%u.%u.%u", &major, &minor, &micro);
    if (parse_rv != 3) {
	/*
	 * We're expected to parse all 3 version levels.
	 * If not, then this must not be an official release.
	 * Return all zeros on the version
	 */
	return (0);
    }

    /* 
     * We allow 8 bits for the major and minor, while
     * allowing 16 bits for the micro.  16 bits for the micro
     * may be beneficial for a continuous delivery model 
     * in the future.
     */
    rv |= (major & 0xFF) << 24;
    rv |= (minor & 0xFF) << 16;
    rv |= micro & 0xFF;
    return rv;
}

/* Release (maybe partially allocated) stream. */
static void
srtp_stream_free(srtp_stream_ctx_t *str) {
  unsigned int i = 0;
  srtp_session_keys_t *session_keys = NULL;

  for (i = 0; i < str->num_master_keys; i++) {
    session_keys = &str->session_keys[i];

    if (session_keys->rtp_xtn_hdr_cipher) {
      srtp_cipher_dealloc(session_keys->rtp_xtn_hdr_cipher);
    }

    if (session_keys->rtcp_cipher) {
      srtp_cipher_dealloc(session_keys->rtcp_cipher);
    }

    if (session_keys->rtcp_auth) {
      srtp_auth_dealloc(session_keys->rtcp_auth);
    }

    if (session_keys->rtp_cipher) {
      srtp_cipher_dealloc(session_keys->rtp_cipher);
    }

    if (session_keys->rtp_auth) {
      srtp_auth_dealloc(session_keys->rtp_auth);
    }

    if (session_keys->mki_id) {
      srtp_crypto_free(session_keys->mki_id);
    }

    if (session_keys->limit) {
      srtp_crypto_free(session_keys->limit);
    }
  }

  srtp_crypto_free(str->session_keys);

  if (str->enc_xtn_hdr) {
    srtp_crypto_free(str->enc_xtn_hdr);
  }

  srtp_crypto_free(str);
}

srtp_err_status_t
srtp_stream_alloc(srtp_stream_ctx_t **str_ptr,
		  const srtp_policy_t *p) {
  srtp_stream_ctx_t *str;
  srtp_err_status_t stat;
  unsigned int i = 0;
  srtp_session_keys_t *session_keys = NULL;

  /*
   * This function allocates the stream context, rtp and rtcp ciphers
   * and auth functions, and key limit structure.  If there is a
   * failure during allocation, we free all previously allocated
   * memory and return a failure code.  The code could probably 
   * be improved, but it works and should be clear.
   */

  /* allocate srtp stream and set str_ptr */
  str = (srtp_stream_ctx_t *) srtp_crypto_alloc(sizeof(srtp_stream_ctx_t));
  if (str == NULL)
    return srtp_err_status_alloc_fail;

  memset(str, 0, sizeof(srtp_stream_ctx_t));
  *str_ptr = str;

  /* To keep backwards API compatible if someone is using multiple master
   * keys then key should be set to NULL
   */
  if (p->key != NULL) {
      str->num_master_keys = 1;
  } else {
      str->num_master_keys = p->num_master_keys;
  }

  str->session_keys = (srtp_session_keys_t *)srtp_crypto_alloc(
      sizeof(srtp_session_keys_t) * str->num_master_keys);

  if (str->session_keys == NULL) {
      srtp_stream_free(str);
      return srtp_err_status_alloc_fail;
  }

  memset(str->session_keys, 0, sizeof(srtp_session_keys_t) * str->num_master_keys);

  for (i = 0; i < str->num_master_keys; i++) {
    session_keys = &str->session_keys[i];

    /* allocate cipher */ 
    stat = srtp_crypto_kernel_alloc_cipher(p->rtp.cipher_type,
                                           &session_keys->rtp_cipher,
                                           p->rtp.cipher_key_len,
				           p->rtp.auth_tag_len);
    if (stat) {
      srtp_stream_free(str);
      return stat;
    }

    /* allocate auth function */
    stat = srtp_crypto_kernel_alloc_auth(p->rtp.auth_type,
                                         &session_keys->rtp_auth,
                                         p->rtp.auth_key_len,
                                         p->rtp.auth_tag_len);
    if (stat) {
      srtp_stream_free(str);
      return stat;
    }

    /*
     * ...and now the RTCP-specific initialization - first, allocate
     * the cipher 
     */
    stat = srtp_crypto_kernel_alloc_cipher(p->rtcp.cipher_type,
                                           &session_keys->rtcp_cipher,
                                           p->rtcp.cipher_key_len,
                                           p->rtcp.auth_tag_len);
    if (stat) {
      srtp_stream_free(str);
      return stat;
    }

    /* allocate auth function */
    stat = srtp_crypto_kernel_alloc_auth(p->rtcp.auth_type,
                                         &session_keys->rtcp_auth,
                                         p->rtcp.auth_key_len,
                                         p->rtcp.auth_tag_len);
    if (stat) {
      srtp_stream_free(str);
      return stat;
    }
   
    session_keys->mki_id = NULL;

    /* allocate key limit structure */
    session_keys->limit = (srtp_key_limit_ctx_t*) srtp_crypto_alloc(sizeof(srtp_key_limit_ctx_t));
    if (session_keys->limit == NULL) {
        srtp_stream_free(str);
        return srtp_err_status_alloc_fail;
    }
  }

  /* allocate ekt data associated with stream */
  stat = srtp_ekt_alloc(&str->ekt, p->ekt);
  if (stat) {
    srtp_stream_free(str);
    return stat;
  }

  if (p->enc_xtn_hdr && p->enc_xtn_hdr_count > 0) {
    srtp_cipher_type_id_t enc_xtn_hdr_cipher_type;
    int enc_xtn_hdr_cipher_key_len;

    str->enc_xtn_hdr = (int*) srtp_crypto_alloc(p->enc_xtn_hdr_count * sizeof(p->enc_xtn_hdr[0]));
    if (!str->enc_xtn_hdr) {
      srtp_stream_free(str);
      return srtp_err_status_alloc_fail;
    }
    memcpy(str->enc_xtn_hdr, p->enc_xtn_hdr, p->enc_xtn_hdr_count * sizeof(p->enc_xtn_hdr[0]));
    str->enc_xtn_hdr_count = p->enc_xtn_hdr_count;

    /* For GCM ciphers, the corresponding ICM cipher is used for header extensions encryption. */
    switch (p->rtp.cipher_type) {
    case SRTP_AES_GCM_128:
      enc_xtn_hdr_cipher_type = SRTP_AES_ICM_128;
      enc_xtn_hdr_cipher_key_len = SRTP_AES_ICM_128_KEY_LEN_WSALT;
      break;
    case SRTP_AES_GCM_256:
      enc_xtn_hdr_cipher_type = SRTP_AES_ICM_256;
      enc_xtn_hdr_cipher_key_len = SRTP_AES_ICM_256_KEY_LEN_WSALT;
      break;
    default:
      enc_xtn_hdr_cipher_type = p->rtp.cipher_type;
      enc_xtn_hdr_cipher_key_len = p->rtp.cipher_key_len;
      break;
    }

    for (i = 0; i < str->num_master_keys; i++) {
      session_keys = &str->session_keys[i];

      /* allocate cipher for extensions header encryption */
      stat = srtp_crypto_kernel_alloc_cipher(enc_xtn_hdr_cipher_type,
                                             &session_keys->rtp_xtn_hdr_cipher,
                                             enc_xtn_hdr_cipher_key_len,
                                             0);
      if (stat) {
        srtp_stream_free(str);
        return stat;
      }
    }
  } else {
    for (i = 0; i < str->num_master_keys; i++) {
      session_keys = &str->session_keys[i];
      session_keys->rtp_xtn_hdr_cipher = NULL;
    }

    str->enc_xtn_hdr = NULL;
    str->enc_xtn_hdr_count = 0;
  }

  return srtp_err_status_ok;
}

srtp_err_status_t
srtp_stream_dealloc(srtp_stream_ctx_t *stream, srtp_stream_ctx_t *stream_template) {
  srtp_err_status_t status;
  unsigned int i = 0;
  srtp_session_keys_t *session_keys = NULL;
  srtp_session_keys_t *template_session_keys = NULL;

  /*
   * we use a conservative deallocation strategy - if any deallocation
   * fails, then we report that fact without trying to deallocate
   * anything else
   */
  for ( i = 0; i < stream->num_master_keys; i++) {
    session_keys = &stream->session_keys[i];

    if (stream_template) {
      template_session_keys = &stream_template->session_keys[i];
    } else {
      template_session_keys = NULL;
    }

    /* deallocate cipher, if it is not the same as that in template */
    if (template_session_keys
        && session_keys->rtp_cipher == template_session_keys->rtp_cipher) {
       /* do nothing */
    } else {
       status = srtp_cipher_dealloc(session_keys->rtp_cipher);
       if (status)
         return status;
    }

    /* deallocate auth function, if it is not the same as that in template */
    if (template_session_keys
        && session_keys->rtp_auth == template_session_keys->rtp_auth) {
       /* do nothing */
    } else {
      status = srtp_auth_dealloc(session_keys->rtp_auth);
      if (status)
        return status;
    }

    if (template_session_keys
        && session_keys->rtp_xtn_hdr_cipher == template_session_keys->rtp_xtn_hdr_cipher) {
       /* do nothing */
    } else if (session_keys->rtp_xtn_hdr_cipher) {
      status = srtp_cipher_dealloc(session_keys->rtp_xtn_hdr_cipher);
      if (status)
        return status;
    }

    /*
     * deallocate rtcp cipher, if it is not the same as that in
     * template
     */
    if (template_session_keys
        && session_keys->rtcp_cipher == template_session_keys->rtcp_cipher) {
      /* do nothing */
    } else {
      status = srtp_cipher_dealloc(session_keys->rtcp_cipher);
      if (status)
        return status;
    }

    /*
     * deallocate rtcp auth function, if it is not the same as that in
     * template
     */
    if (template_session_keys
        && session_keys->rtcp_auth == template_session_keys->rtcp_auth) {
      /* do nothing */
    } else {
      status = srtp_auth_dealloc(session_keys->rtcp_auth);
      if (status)
        return status;
    }

    /*
     * zeroize the salt value
     */
    octet_string_set_to_zero(session_keys->salt, SRTP_AEAD_SALT_LEN);
    octet_string_set_to_zero(session_keys->c_salt, SRTP_AEAD_SALT_LEN);

    if (session_keys->mki_id) {
      octet_string_set_to_zero(session_keys->mki_id, session_keys->mki_size);
      srtp_crypto_free(session_keys->mki_id);
      session_keys->mki_id = NULL;
    }

    /* deallocate key usage limit, if it is not the same as that in template */
    if (template_session_keys
        && session_keys->limit == template_session_keys->limit) {
        /* do nothing */
    } else {
      srtp_crypto_free(session_keys->limit);
    }

  }

  if (stream_template
      && stream->session_keys == stream_template->session_keys) {
      /* do nothing */
  } else {
    srtp_crypto_free(stream->session_keys);
  }

  status = srtp_rdbx_dealloc(&stream->rtp_rdbx);
  if (status)
    return status;

  /* DAM - need to deallocate EKT here */

  if (stream_template
      && stream->enc_xtn_hdr == stream_template->enc_xtn_hdr) {
    /* do nothing */
  } else if (stream->enc_xtn_hdr) {
    srtp_crypto_free(stream->enc_xtn_hdr);
  }

  /* deallocate srtp stream context */
  srtp_crypto_free(stream);

  return srtp_err_status_ok;
}


/*
 * srtp_stream_clone(stream_template, new) allocates a new stream and
 * initializes it using the cipher and auth of the stream_template
 * 
 * the only unique data in a cloned stream is the replay database and
 * the SSRC
 */

srtp_err_status_t
srtp_stream_clone(const srtp_stream_ctx_t *stream_template, 
		  uint32_t ssrc, 
		  srtp_stream_ctx_t **str_ptr) {
  srtp_err_status_t status;
  srtp_stream_ctx_t *str;
  unsigned int i = 0;
  srtp_session_keys_t *session_keys = NULL;
  const srtp_session_keys_t *template_session_keys = NULL;

  debug_print(mod_srtp, "cloning stream (SSRC: 0x%08x)", ntohl(ssrc));

  /* allocate srtp stream and set str_ptr */
  str = (srtp_stream_ctx_t *) srtp_crypto_alloc(sizeof(srtp_stream_ctx_t));
  if (str == NULL)
    return srtp_err_status_alloc_fail;
  *str_ptr = str;  

  str->num_master_keys = stream_template->num_master_keys;
  str->session_keys = (srtp_session_keys_t *)srtp_crypto_alloc(
      sizeof(srtp_session_keys_t) * str->num_master_keys);

  if (str->session_keys == NULL) {
    srtp_crypto_free(*str_ptr);
    *str_ptr = NULL;
    return srtp_err_status_alloc_fail;
  }

  for (i = 0; i < stream_template->num_master_keys; i++){
    session_keys = &str->session_keys[i];
    template_session_keys = &stream_template->session_keys[i];

    /* set cipher and auth pointers to those of the template */
    session_keys->rtp_cipher  = template_session_keys->rtp_cipher;
    session_keys->rtp_auth    = template_session_keys->rtp_auth;
    session_keys->rtp_xtn_hdr_cipher = template_session_keys->rtp_xtn_hdr_cipher;
    session_keys->rtcp_cipher = template_session_keys->rtcp_cipher;
    session_keys->rtcp_auth   = template_session_keys->rtcp_auth;
    session_keys->mki_size = template_session_keys->mki_size;

    if (template_session_keys->mki_size == 0) {
      session_keys->mki_id = NULL;
    } else {
      session_keys->mki_id = srtp_crypto_alloc(template_session_keys->mki_size);

      if (session_keys->mki_id == NULL) {
        return srtp_err_status_init_fail;
      }
      memset(session_keys->mki_id, 0x0, session_keys->mki_size);
      memcpy(session_keys->mki_id, template_session_keys->mki_id, session_keys->mki_size);
    }
    /* Copy the salt values */
    memcpy(session_keys->salt, template_session_keys->salt, SRTP_AEAD_SALT_LEN);
    memcpy(session_keys->c_salt, template_session_keys->c_salt, SRTP_AEAD_SALT_LEN);

    /* set key limit to point to that of the template */
    status = srtp_key_limit_clone(template_session_keys->limit, &session_keys->limit);
    if (status) { 
      srtp_crypto_free(*str_ptr);
      *str_ptr = NULL;
      return status;
    }
  }


  /* initialize replay databases */
  status = srtp_rdbx_init(&str->rtp_rdbx,
		     srtp_rdbx_get_window_size(&stream_template->rtp_rdbx));
  if (status) {
    srtp_crypto_free(*str_ptr);
    *str_ptr = NULL;
    return status;
  }
  srtp_rdb_init(&str->rtcp_rdb);
  str->allow_repeat_tx = stream_template->allow_repeat_tx;
  
  /* set ssrc to that provided */
  str->ssrc = ssrc;

  /* set direction and security services */
  str->direction     = stream_template->direction;
  str->rtp_services  = stream_template->rtp_services;
  str->rtcp_services = stream_template->rtcp_services;

  /* set pointer to EKT data associated with stream */
  str->ekt = stream_template->ekt;

  /* copy information about extensions header encryption */
  str->enc_xtn_hdr = stream_template->enc_xtn_hdr;
  str->enc_xtn_hdr_count = stream_template->enc_xtn_hdr_count;

  /* defensive coding */
  str->next = NULL;
  return srtp_err_status_ok;
}


/*
 * key derivation functions, internal to libSRTP
 *
 * srtp_kdf_t is a key derivation context
 *
 * srtp_kdf_init(&kdf, cipher_id, k, keylen) initializes kdf to use cipher
 * described by cipher_id, with the master key k with length in octets keylen.
 * 
 * srtp_kdf_generate(&kdf, l, kl, keylen) derives the key
 * corresponding to label l and puts it into kl; the length
 * of the key in octets is provided as keylen.  this function
 * should be called once for each subkey that is derived.
 *
 * srtp_kdf_clear(&kdf) zeroizes and deallocates the kdf state
 */

typedef enum {
  label_rtp_encryption  = 0x00,
  label_rtp_msg_auth    = 0x01,
  label_rtp_salt        = 0x02,
  label_rtcp_encryption = 0x03,
  label_rtcp_msg_auth   = 0x04,
  label_rtcp_salt       = 0x05,
  label_rtp_header_encryption = 0x06,
  label_rtp_header_salt = 0x07
} srtp_prf_label;

#define MAX_SRTP_KEY_LEN 256

#if defined(OPENSSL) && defined(OPENSSL_KDF)
#define MAX_SRTP_AESKEY_LEN 32
#define MAX_SRTP_SALT_LEN 14 

/*
 * srtp_kdf_t represents a key derivation function.  The SRTP
 * default KDF is the only one implemented at present.
 */
typedef struct { 
    uint8_t master_key[MAX_SRTP_AESKEY_LEN];
    uint8_t master_salt[MAX_SRTP_SALT_LEN];
    const EVP_CIPHER *evp;
} srtp_kdf_t;


static srtp_err_status_t srtp_kdf_init(srtp_kdf_t *kdf, const uint8_t *key, int key_len, int salt_len) 
{
    memset(kdf, 0x0, sizeof(srtp_kdf_t));

    /* The NULL cipher has zero key length */
    if (key_len == 0) return srtp_err_status_ok;

    if ((key_len > MAX_SRTP_AESKEY_LEN) || (salt_len > MAX_SRTP_SALT_LEN)) {
        return srtp_err_status_bad_param;
    }
    switch (key_len) {
    case SRTP_AES_256_KEYSIZE:
        kdf->evp = EVP_aes_256_ctr();
        break;
    case SRTP_AES_192_KEYSIZE:
        kdf->evp = EVP_aes_192_ctr();
        break;
    case SRTP_AES_128_KEYSIZE:
        kdf->evp = EVP_aes_128_ctr();
        break;
    default:
        return srtp_err_status_bad_param;
        break;
    }
    memcpy(kdf->master_key, key, key_len); 
    memcpy(kdf->master_salt, key+key_len, salt_len); 
    return srtp_err_status_ok;
}

static srtp_err_status_t srtp_kdf_generate(srtp_kdf_t *kdf, srtp_prf_label label, uint8_t *key, unsigned int length) 
{
    int ret;

    /* The NULL cipher will not have an EVP */
    if (!kdf->evp) return srtp_err_status_ok;
    octet_string_set_to_zero(key, length);

    /*
     * Invoke the OpenSSL SRTP KDF function
     * This is useful if OpenSSL is in FIPS mode and FIP
     * compliance is required for SRTP.
     */
    ret = kdf_srtp(kdf->evp, (char *)&kdf->master_key, (char *)&kdf->master_salt, NULL, NULL, label, (char *)key);
    if (ret == -1) {
        return (srtp_err_status_algo_fail);
    }

    return srtp_err_status_ok;
}

static srtp_err_status_t srtp_kdf_clear(srtp_kdf_t *kdf) {
    octet_string_set_to_zero(kdf->master_key, MAX_SRTP_AESKEY_LEN);
    octet_string_set_to_zero(kdf->master_salt, MAX_SRTP_SALT_LEN);
    kdf->evp = NULL;

    return srtp_err_status_ok;  
}

#else /* if OPENSSL_KDF */

/*
 * srtp_kdf_t represents a key derivation function.  The SRTP
 * default KDF is the only one implemented at present.
 */
typedef struct { 
    srtp_cipher_t *cipher;    /* cipher used for key derivation  */  
} srtp_kdf_t;

static srtp_err_status_t srtp_kdf_init(srtp_kdf_t *kdf, const uint8_t *key, int key_len)
{
    srtp_cipher_type_id_t cipher_id;
    switch (key_len) {
    case SRTP_AES_ICM_256_KEY_LEN_WSALT:
        cipher_id = SRTP_AES_ICM_256;
        break;
    case SRTP_AES_ICM_192_KEY_LEN_WSALT:
        cipher_id = SRTP_AES_ICM_192;
        break;
    case SRTP_AES_ICM_128_KEY_LEN_WSALT:
        cipher_id = SRTP_AES_ICM_128;
        break;
    default:
        return srtp_err_status_bad_param;
        break;
    }

    srtp_err_status_t stat;
    stat = srtp_crypto_kernel_alloc_cipher(cipher_id, &kdf->cipher, key_len, 0);
    if (stat) return stat;

    stat = srtp_cipher_init(kdf->cipher, key);
    if (stat) {
        srtp_cipher_dealloc(kdf->cipher);
        return stat;
    }
    return srtp_err_status_ok;
}

static srtp_err_status_t srtp_kdf_generate(srtp_kdf_t *kdf, srtp_prf_label label, uint8_t *key, unsigned int length) 
{
    srtp_err_status_t status;
    v128_t nonce;
  
    /* set eigth octet of nonce to <label>, set the rest of it to zero */
    v128_set_to_zero(&nonce);
    nonce.v8[7] = label;
 
    status = srtp_cipher_set_iv(kdf->cipher, (uint8_t*)&nonce, srtp_direction_encrypt);
    if (status) return status;
  
    /* generate keystream output */
    octet_string_set_to_zero(key, length);
    status = srtp_cipher_encrypt(kdf->cipher, key, &length);
    if (status) return status;

    return srtp_err_status_ok;
}

static srtp_err_status_t srtp_kdf_clear(srtp_kdf_t *kdf) {
    srtp_err_status_t status;
    status = srtp_cipher_dealloc(kdf->cipher);
    if (status) return status;
    kdf->cipher = NULL;
    return srtp_err_status_ok;  
}
#endif /* else OPENSSL_KDF */

/*
 *  end of key derivation functions 
 */



/* Get the base key length corresponding to a given combined key+salt
 * length for the given cipher.
 * TODO: key and salt lengths should be separate fields in the policy.  */
static inline int base_key_length(const srtp_cipher_type_t *cipher, int key_length)
{
  switch (cipher->id) {
  case SRTP_AES_ICM_128:
  case SRTP_AES_ICM_192:
  case SRTP_AES_ICM_256:
    /* The legacy modes are derived from
     * the configured key length on the policy */
    return key_length - SRTP_SALT_LEN;
    break;
  case SRTP_AES_GCM_128:
    return key_length - SRTP_AEAD_SALT_LEN;
    break;
  case SRTP_AES_GCM_256:
      return key_length - SRTP_AEAD_SALT_LEN;
    break;
  default:
    return key_length;
    break;
  }
}

unsigned int
srtp_validate_policy_master_keys(const srtp_policy_t *policy)
{
    int i = 0;

    if (policy->key == NULL) {
        if (policy->num_master_keys <= 0)
            return 0;

        if (policy->num_master_keys > SRTP_MAX_NUM_MASTER_KEYS)
	    return 0;
	
        for (i = 0; i < policy->num_master_keys; i++) {
            if (policy->keys[i]->key == NULL)
                return 0;
	    if (policy->keys[i]->mki_size > SRTP_MAX_MKI_LEN)
		return 0;
        }
    }

    return 1;
}

srtp_session_keys_t*
srtp_get_session_keys_with_mki_index(srtp_stream_ctx_t *stream,
                                     unsigned int use_mki,
                                     unsigned int mki_index) {
    if (use_mki) {
        if (mki_index < stream->num_master_keys) {
            return &stream->session_keys[mki_index];
        }
    }

    return &stream->session_keys[0];
}

unsigned int
srtp_inject_mki(uint8_t *mki_tag_location, srtp_session_keys_t* session_keys,
                unsigned int use_mki)
{
    unsigned int mki_size = 0;

    if (use_mki) {
        mki_size = session_keys->mki_size;

        if (mki_size != 0) {
            // Write MKI into memory
            memcpy(mki_tag_location, session_keys->mki_id, mki_size);
        }
    }

    return mki_size;
}

srtp_err_status_t
srtp_stream_init_all_master_keys(srtp_stream_ctx_t *srtp,
                                 unsigned char *key,
                                 srtp_master_key_t **keys,
                                 const unsigned int max_master_keys) {
    int i = 0;
    srtp_err_status_t status = srtp_err_status_ok;
    srtp_master_key_t single_master_key;

    if ( key != NULL ) {
        srtp->num_master_keys = 1;
        single_master_key.key = key;
        single_master_key.mki_id = NULL;
        single_master_key.mki_size = 0;
        status = srtp_stream_init_keys(srtp, &single_master_key, 0);
    } else {
        srtp->num_master_keys = max_master_keys;

        for (i = 0; i < srtp->num_master_keys && i < SRTP_MAX_NUM_MASTER_KEYS; i++) {
            status = srtp_stream_init_keys(srtp, keys[i], i);

            if (status) {
                return status;
            }
        }
    }

    return status;
}

srtp_err_status_t
srtp_stream_init_keys(srtp_stream_ctx_t *srtp, srtp_master_key_t *master_key,
                      const unsigned int current_mki_index) {
  srtp_err_status_t stat;
  srtp_kdf_t kdf;
  uint8_t tmp_key[MAX_SRTP_KEY_LEN];
  int kdf_keylen = 30, rtp_keylen, rtcp_keylen;
  int rtp_base_key_len, rtp_salt_len;
  int rtcp_base_key_len, rtcp_salt_len;
  srtp_session_keys_t *session_keys = NULL;
  unsigned char *key = master_key->key;

  /* If RTP or RTCP have a key length > AES-128, assume matching kdf. */
  /* TODO: kdf algorithm, master key length, and master salt length should
   * be part of srtp_policy_t. */
  session_keys = &srtp->session_keys[current_mki_index];

   /* initialize key limit to maximum value */
#ifdef NO_64BIT_MATH
{
   uint64_t temp;
   temp = make64(UINT_MAX,UINT_MAX);
   srtp_key_limit_set(session_keys->limit, temp);
}
#else
   srtp_key_limit_set(session_keys->limit, 0xffffffffffffLL);
#endif


  if ( master_key->mki_size != 0 ) {
      session_keys->mki_id = srtp_crypto_alloc(master_key->mki_size);

      if (session_keys->mki_id == NULL) {
        return srtp_err_status_init_fail;
      }
      memset(session_keys->mki_id, 0x0, master_key->mki_size);
      memcpy(session_keys->mki_id, master_key->mki_id, master_key->mki_size);
  } else {
      session_keys->mki_id = NULL;
  }

  session_keys->mki_size = master_key->mki_size;

  rtp_keylen = srtp_cipher_get_key_length(session_keys->rtp_cipher);
  rtcp_keylen = srtp_cipher_get_key_length(session_keys->rtcp_cipher);
  rtp_base_key_len = base_key_length(session_keys->rtp_cipher->type, rtp_keylen);
  rtp_salt_len = rtp_keylen - rtp_base_key_len;

  if (rtp_keylen > kdf_keylen) {
    kdf_keylen = 46;  /* AES-CTR mode is always used for KDF */
  }

  if (rtcp_keylen > kdf_keylen) {
    kdf_keylen = 46;  /* AES-CTR mode is always used for KDF */
  }

  debug_print(mod_srtp, "srtp key len: %d", rtp_keylen);
  debug_print(mod_srtp, "srtcp key len: %d", rtcp_keylen);
  debug_print(mod_srtp, "base key len: %d", rtp_base_key_len);
  debug_print(mod_srtp, "kdf key len: %d", kdf_keylen);
  debug_print(mod_srtp, "rtp salt len: %d", rtp_salt_len);

  /* 
   * Make sure the key given to us is 'zero' appended.  GCM
   * mode uses a shorter master SALT (96 bits), but still relies on 
   * the legacy CTR mode KDF, which uses a 112 bit master SALT.
   */
  memset(tmp_key, 0x0, MAX_SRTP_KEY_LEN);
  memcpy(tmp_key, key, (rtp_base_key_len + rtp_salt_len));

  /* initialize KDF state     */
#if defined(OPENSSL) && defined(OPENSSL_KDF)
  stat = srtp_kdf_init(&kdf, (const uint8_t *)tmp_key, rtp_base_key_len, rtp_salt_len); 
#else
  stat = srtp_kdf_init(&kdf, (const uint8_t *)tmp_key, kdf_keylen);
#endif
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }
  
  /* generate encryption key  */
  stat = srtp_kdf_generate(&kdf, label_rtp_encryption, 
			   tmp_key, rtp_base_key_len);
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }
  debug_print(mod_srtp, "cipher key: %s", 
	      srtp_octet_string_hex_string(tmp_key, rtp_base_key_len));

  /* 
   * if the cipher in the srtp context uses a salt, then we need
   * to generate the salt value
   */
  if (rtp_salt_len > 0) {
    debug_print(mod_srtp, "found rtp_salt_len > 0, generating salt", NULL);

    /* generate encryption salt, put after encryption key */
    stat = srtp_kdf_generate(&kdf, label_rtp_salt, 
			     tmp_key + rtp_base_key_len, rtp_salt_len);
    if (stat) {
      /* zeroize temp buffer */
      octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
      return srtp_err_status_init_fail;
    }
    memcpy(session_keys->salt, tmp_key + rtp_base_key_len, SRTP_AEAD_SALT_LEN);
  }
  if (rtp_salt_len > 0) {
    debug_print(mod_srtp, "cipher salt: %s",
		srtp_octet_string_hex_string(tmp_key + rtp_base_key_len, rtp_salt_len));
  }

  /* initialize cipher */
  stat = srtp_cipher_init(session_keys->rtp_cipher, tmp_key);
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }

  if (session_keys->rtp_xtn_hdr_cipher) {
    /* generate extensions header encryption key  */
    int rtp_xtn_hdr_keylen;
    int rtp_xtn_hdr_base_key_len;
    int rtp_xtn_hdr_salt_len;
    srtp_kdf_t tmp_kdf;
    srtp_kdf_t *xtn_hdr_kdf;

    if (session_keys->rtp_xtn_hdr_cipher->type != session_keys->rtp_cipher->type) {
      /* With GCM ciphers, the header extensions are still encrypted using the corresponding ICM cipher. */
      /* See https://tools.ietf.org/html/rfc7714#section-8.3 */
      uint8_t tmp_xtn_hdr_key[MAX_SRTP_KEY_LEN];
      rtp_xtn_hdr_keylen = srtp_cipher_get_key_length(session_keys->rtp_xtn_hdr_cipher);
      rtp_xtn_hdr_base_key_len = base_key_length(session_keys->rtp_xtn_hdr_cipher->type,
                                                 rtp_xtn_hdr_keylen);
      rtp_xtn_hdr_salt_len = rtp_xtn_hdr_keylen - rtp_xtn_hdr_base_key_len;
      if (rtp_xtn_hdr_salt_len > rtp_salt_len) {
        switch (session_keys->rtp_cipher->type->id) {
        case SRTP_AES_GCM_128:
        case SRTP_AES_GCM_256:
          /* The shorter GCM salt is padded to the required ICM salt length. */
          rtp_xtn_hdr_salt_len = rtp_salt_len;
          break;
        default:
          /* zeroize temp buffer */
          octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
          return srtp_err_status_bad_param;
        }
      }
      memset(tmp_xtn_hdr_key, 0x0, MAX_SRTP_KEY_LEN);
      memcpy(tmp_xtn_hdr_key, key, (rtp_xtn_hdr_base_key_len + rtp_xtn_hdr_salt_len));
      xtn_hdr_kdf = &tmp_kdf;

      /* initialize KDF state     */
#if defined(OPENSSL) && defined(OPENSSL_KDF)
      stat = srtp_kdf_init(xtn_hdr_kdf, (const uint8_t *)tmp_xtn_hdr_key, rtp_xtn_hdr_base_key_len, rtp_xtn_hdr_salt_len);
#else
      stat = srtp_kdf_init(xtn_hdr_kdf, (const uint8_t *)tmp_xtn_hdr_key, kdf_keylen);
#endif
      octet_string_set_to_zero(tmp_xtn_hdr_key, MAX_SRTP_KEY_LEN);
      if (stat) {
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
      }
    } else {
      /* Reuse main KDF. */
      rtp_xtn_hdr_keylen = rtp_keylen;
      rtp_xtn_hdr_base_key_len = rtp_base_key_len;
      rtp_xtn_hdr_salt_len = rtp_salt_len;
      xtn_hdr_kdf = &kdf;
    }

    stat = srtp_kdf_generate(xtn_hdr_kdf, label_rtp_header_encryption,
           tmp_key, rtp_xtn_hdr_base_key_len);
    if (stat) {
      /* zeroize temp buffer */
      octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
      return srtp_err_status_init_fail;
    }
    debug_print(mod_srtp, "extensions cipher key: %s",
          srtp_octet_string_hex_string(tmp_key, rtp_xtn_hdr_base_key_len));

    /*
     * if the cipher in the srtp context uses a salt, then we need
     * to generate the salt value
     */
    if (rtp_xtn_hdr_salt_len > 0) {
      debug_print(mod_srtp, "found rtp_xtn_hdr_salt_len > 0, generating salt", NULL);

      /* generate encryption salt, put after encryption key */
      stat = srtp_kdf_generate(xtn_hdr_kdf, label_rtp_header_salt,
             tmp_key + rtp_xtn_hdr_base_key_len, rtp_xtn_hdr_salt_len);
      if (stat) {
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
      }
    }
    if (rtp_xtn_hdr_salt_len > 0) {
      debug_print(mod_srtp, "extensions cipher salt: %s",
      srtp_octet_string_hex_string(tmp_key + rtp_xtn_hdr_base_key_len, rtp_xtn_hdr_salt_len));
    }

    /* initialize extensions header cipher */
    stat = srtp_cipher_init(session_keys->rtp_xtn_hdr_cipher, tmp_key);
    if (stat) {
      /* zeroize temp buffer */
      octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
      return srtp_err_status_init_fail;
    }

    if (xtn_hdr_kdf != &kdf) {
      /* release memory for custom header extension encryption kdf */
      stat = srtp_kdf_clear(xtn_hdr_kdf);
      if (stat) {
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
      }
    }
  }

  /* generate authentication key */
  stat = srtp_kdf_generate(&kdf, label_rtp_msg_auth,
			   tmp_key, srtp_auth_get_key_length(session_keys->rtp_auth));
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }
  debug_print(mod_srtp, "auth key:   %s",
	      srtp_octet_string_hex_string(tmp_key, 
				      srtp_auth_get_key_length(session_keys->rtp_auth))); 

  /* initialize auth function */
  stat = srtp_auth_init(session_keys->rtp_auth, tmp_key);
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }

  /*
   * ...now initialize SRTCP keys
   */

  rtcp_base_key_len = base_key_length(session_keys->rtcp_cipher->type, rtcp_keylen);
  rtcp_salt_len = rtcp_keylen - rtcp_base_key_len;
  debug_print(mod_srtp, "rtcp salt len: %d", rtcp_salt_len);
  
  /* generate encryption key  */
  stat = srtp_kdf_generate(&kdf, label_rtcp_encryption, 
			   tmp_key, rtcp_base_key_len);
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }

  /* 
   * if the cipher in the srtp context uses a salt, then we need
   * to generate the salt value
   */
  if (rtcp_salt_len > 0) {
    debug_print(mod_srtp, "found rtcp_salt_len > 0, generating rtcp salt",
		NULL);

    /* generate encryption salt, put after encryption key */
    stat = srtp_kdf_generate(&kdf, label_rtcp_salt, 
			     tmp_key + rtcp_base_key_len, rtcp_salt_len);
    if (stat) {
      /* zeroize temp buffer */
      octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
      return srtp_err_status_init_fail;
    }
    memcpy(session_keys->c_salt, tmp_key + rtcp_base_key_len, SRTP_AEAD_SALT_LEN);
  }
  debug_print(mod_srtp, "rtcp cipher key: %s", 
	      srtp_octet_string_hex_string(tmp_key, rtcp_base_key_len));  
  if (rtcp_salt_len > 0) {
    debug_print(mod_srtp, "rtcp cipher salt: %s",
		srtp_octet_string_hex_string(tmp_key + rtcp_base_key_len, rtcp_salt_len));
  }

  /* initialize cipher */
  stat = srtp_cipher_init(session_keys->rtcp_cipher, tmp_key);
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }

  /* generate authentication key */
  stat = srtp_kdf_generate(&kdf, label_rtcp_msg_auth,
			   tmp_key, srtp_auth_get_key_length(session_keys->rtcp_auth));
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }

  debug_print(mod_srtp, "rtcp auth key:   %s",
	      srtp_octet_string_hex_string(tmp_key, 
		     srtp_auth_get_key_length(session_keys->rtcp_auth))); 

  /* initialize auth function */
  stat = srtp_auth_init(session_keys->rtcp_auth, tmp_key);
  if (stat) {
    /* zeroize temp buffer */
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    return srtp_err_status_init_fail;
  }

  /* clear memory then return */
  stat = srtp_kdf_clear(&kdf);
  octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
  if (stat)
    return srtp_err_status_init_fail;

  return srtp_err_status_ok;
}

srtp_err_status_t
srtp_stream_init(srtp_stream_ctx_t *srtp, 
		  const srtp_policy_t *p) {
  srtp_err_status_t err;

   debug_print(mod_srtp, "initializing stream (SSRC: 0x%08x)", 
	       p->ssrc.value);

   /* initialize replay database */
   /* window size MUST be at least 64.  MAY be larger.  Values more than
    * 2^15 aren't meaningful due to how extended sequence numbers are
    * calculated.   Let a window size of 0 imply the default value. */

   if (p->window_size != 0 && (p->window_size < 64 || p->window_size >= 0x8000))
     return srtp_err_status_bad_param;

   if (p->window_size != 0)
     err = srtp_rdbx_init(&srtp->rtp_rdbx, p->window_size);
   else
     err = srtp_rdbx_init(&srtp->rtp_rdbx, 128);
   if (err) return err;

   /* set the SSRC value */
   srtp->ssrc = htonl(p->ssrc.value);

   /* set the security service flags */
   srtp->rtp_services  = p->rtp.sec_serv;
   srtp->rtcp_services = p->rtcp.sec_serv;

   /*
    * set direction to unknown - this flag gets checked in srtp_protect(),
    * srtp_unprotect(), srtp_protect_rtcp(), and srtp_unprotect_rtcp(), and 
    * gets set appropriately if it is set to unknown.
    */
   srtp->direction = dir_unknown;

   /* initialize SRTCP replay database */
   srtp_rdb_init(&srtp->rtcp_rdb);

   /* initialize allow_repeat_tx */
   /* guard against uninitialized memory: allow only 0 or 1 here */
   if (p->allow_repeat_tx != 0 && p->allow_repeat_tx != 1) {
     srtp_rdbx_dealloc(&srtp->rtp_rdbx);
     return srtp_err_status_bad_param;
   }
   srtp->allow_repeat_tx = p->allow_repeat_tx;

   /* DAM - no RTCP key limit at present */

   /* initialize keys */
   err = srtp_stream_init_all_master_keys(srtp, p->key, p->keys, p->num_master_keys);
   if (err) {
     srtp_rdbx_dealloc(&srtp->rtp_rdbx);
     return err;
   }

   /* 
    * if EKT is in use, then initialize the EKT data associated with
    * the stream
    */
   err = srtp_ekt_stream_init_from_policy(srtp->ekt, p->ekt);
   if (err) {
     srtp_rdbx_dealloc(&srtp->rtp_rdbx);
     return err;
   }

   return srtp_err_status_ok;  
 }


 /*
  * srtp_event_reporter is an event handler function that merely
  * reports the events that are reported by the callbacks
  */

 void
 srtp_event_reporter(srtp_event_data_t *data) {

   srtp_err_report(srtp_err_level_warning, "srtp: in stream 0x%x: ", 
                   data->ssrc);

   switch(data->event) {
   case event_ssrc_collision:
     srtp_err_report(srtp_err_level_warning, "\tSSRC collision\n");
     break;
   case event_key_soft_limit:
     srtp_err_report(srtp_err_level_warning, "\tkey usage soft limit reached\n");
     break;
   case event_key_hard_limit:
     srtp_err_report(srtp_err_level_warning, "\tkey usage hard limit reached\n");
     break;
   case event_packet_index_limit:
     srtp_err_report(srtp_err_level_warning, "\tpacket index limit reached\n");
     break;
   default:
     srtp_err_report(srtp_err_level_warning, "\tunknown event reported to handler\n");
   }
 }

 /*
  * srtp_event_handler is a global variable holding a pointer to the
  * event handler function; this function is called for any unexpected
  * event that needs to be handled out of the SRTP data path.  see
  * srtp_event_t in srtp.h for more info
  *
  * it is okay to set srtp_event_handler to NULL, but we set 
  * it to the srtp_event_reporter.
  */

 static srtp_event_handler_func_t *srtp_event_handler = srtp_event_reporter;

 srtp_err_status_t
 srtp_install_event_handler(srtp_event_handler_func_t func) {

   /* 
    * note that we accept NULL arguments intentionally - calling this
    * function with a NULL arguments removes an event handler that's
    * been previously installed
    */

   /* set global event handling function */
   srtp_event_handler = func;
   return srtp_err_status_ok;
 }


/*
 * Check if the given extension header id is / should be encrypted.
 * Returns 1 if yes, otherwise 0.
 */
static int
srtp_protect_extension_header(srtp_stream_ctx_t *stream, int id) {
  int* enc_xtn_hdr = stream->enc_xtn_hdr;
  int count = stream->enc_xtn_hdr_count;

  if (!enc_xtn_hdr || count <= 0) {
    return 0;
  }

  while (count > 0) {
    if (*enc_xtn_hdr == id) {
      return 1;
    }

    enc_xtn_hdr++;
    count--;
  }
  return 0;
}


/*
 * extensions header encryption RFC 6904
 */
static srtp_err_status_t
srtp_process_header_encryption(srtp_stream_ctx_t *stream,
                               srtp_hdr_xtnd_t *xtn_hdr,
                               srtp_session_keys_t *session_keys) {
  srtp_err_status_t status;
  uint8_t keystream[257];  /* Maximum 2 bytes header + 255 bytes data. */
  int keystream_pos;
  uint8_t* xtn_hdr_data = ((uint8_t *)xtn_hdr) + octets_in_rtp_extn_hdr;
  uint8_t* xtn_hdr_end = xtn_hdr_data + (ntohs(xtn_hdr->length) * sizeof(uint32_t));

  if (ntohs(xtn_hdr->profile_specific) == 0xbede) {
    /* RFC 5285, section 4.2. One-Byte Header */
    while (xtn_hdr_data < xtn_hdr_end) {
      uint8_t xid = (*xtn_hdr_data & 0xf0) >> 4;
      unsigned int xlen = (*xtn_hdr_data & 0x0f) + 1;
      uint32_t xlen_with_header = 1+xlen;
      xtn_hdr_data++;

      if (xtn_hdr_data + xlen > xtn_hdr_end)
        return srtp_err_status_parse_err;

      if (xid == 15) {
        /* found header 15, stop further processing. */
        break;
      }

      status = srtp_cipher_output(session_keys->rtp_xtn_hdr_cipher,
                                  keystream, &xlen_with_header);
      if (status)
        return srtp_err_status_cipher_fail;

      if (srtp_protect_extension_header(stream, xid)) {
        keystream_pos = 1;
        while (xlen > 0) {
          *xtn_hdr_data ^= keystream[keystream_pos++];
          xtn_hdr_data++;
          xlen--;
        }
      } else {
        xtn_hdr_data += xlen;
      }

      /* skip padding bytes. */
      while (xtn_hdr_data < xtn_hdr_end && *xtn_hdr_data == 0) {
        xtn_hdr_data++;
      }
    }
  } else if ((ntohs(xtn_hdr->profile_specific) & 0x1fff) == 0x100) {
    /* RFC 5285, section 4.3. Two-Byte Header */
    while (xtn_hdr_data + 1 < xtn_hdr_end) {
      uint8_t xid = *xtn_hdr_data;
      unsigned int xlen = *(xtn_hdr_data+1);
      uint32_t xlen_with_header = 2+xlen;
      xtn_hdr_data += 2;

      if (xtn_hdr_data + xlen > xtn_hdr_end)
        return srtp_err_status_parse_err;

      status = srtp_cipher_output(session_keys->rtp_xtn_hdr_cipher,
                                  keystream, &xlen_with_header);
      if (status)
        return srtp_err_status_cipher_fail;

      if (xlen > 0 && srtp_protect_extension_header(stream, xid)) {
        keystream_pos = 2;
        while (xlen > 0) {
          *xtn_hdr_data ^= keystream[keystream_pos++];
          xtn_hdr_data++;
          xlen--;
        }
      } else {
        xtn_hdr_data += xlen;
      }

      /* skip padding bytes. */
      while (xtn_hdr_data < xtn_hdr_end && *xtn_hdr_data == 0) {
        xtn_hdr_data++;
      }
    }
  } else {
    /* unsupported extension header format. */
    return srtp_err_status_parse_err;
  }

  return srtp_err_status_ok;
}


/*
 * AEAD uses a new IV formation method.  This function implements
 * section 8.1. (SRTP IV Formation for AES-GCM) of RFC7714.
 * The calculation is defined as, where (+) is the xor operation:
 *
 *
 *              0  0  0  0  0  0  0  0  0  0  1  1
 *              0  1  2  3  4  5  6  7  8  9  0  1
 *            +--+--+--+--+--+--+--+--+--+--+--+--+
 *            |00|00|    SSRC   |     ROC   | SEQ |---+
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *                                                    |
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *            |         Encryption Salt           |->(+)
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *                                                    |
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *            |       Initialization Vector       |<--+
 *            +--+--+--+--+--+--+--+--+--+--+--+--+*
 *
 * Input:  *session_keys - pointer to SRTP stream context session keys,
 *                         used to retrieve the SALT 
 *         *iv     - Pointer to receive the calculated IV
 *         *seq    - The ROC and SEQ value to use for the
 *                   IV calculation.
 *         *hdr    - The RTP header, used to get the SSRC value
 *
 */

static void srtp_calc_aead_iv(srtp_session_keys_t *session_keys, v128_t *iv,
                              srtp_xtd_seq_num_t *seq, srtp_hdr_t *hdr)
{
    v128_t	in;
    v128_t	salt;

#ifdef NO_64BIT_MATH
    uint32_t local_roc = ((high32(*seq) << 16) |
                         (low32(*seq) >> 16));
    uint16_t local_seq = (uint16_t) (low32(*seq));
#else
    uint32_t local_roc = (uint32_t)(*seq >> 16);
    uint16_t local_seq = (uint16_t) *seq;
#endif

    memset(&in, 0, sizeof(v128_t));
    memset(&salt, 0, sizeof(v128_t));

    in.v16[5] = htons(local_seq);
    local_roc = htonl(local_roc);
    memcpy(&in.v16[3], &local_roc, sizeof(local_roc));

    /*
     * Copy in the RTP SSRC value
     */
    memcpy(&in.v8[2], &hdr->ssrc, 4);
    debug_print(mod_srtp, "Pre-salted RTP IV = %s\n", v128_hex_string(&in));

    /*
     * Get the SALT value from the context
     */
    memcpy(salt.v8, session_keys->salt, SRTP_AEAD_SALT_LEN);
    debug_print(mod_srtp, "RTP SALT = %s\n", v128_hex_string(&salt));

    /*
     * Finally, apply tyhe SALT to the input
     */
    v128_xor(iv, &in, &salt);
}


srtp_session_keys_t* 
srtp_get_session_keys(srtp_stream_ctx_t *stream, uint8_t* hdr,
                      const unsigned int* pkt_octet_len,
                      unsigned int* mki_size) {
  unsigned int base_mki_start_location = *pkt_octet_len;
  unsigned int mki_start_location = 0;
  unsigned int tag_len = 0;
  unsigned int i = 0;

  // Determine the authentication tag size
  if (stream->session_keys[0].rtp_cipher->algorithm == SRTP_AES_GCM_128 ||
      stream->session_keys[0].rtp_cipher->algorithm == SRTP_AES_GCM_256) {
      tag_len = 0;
  } else {
      tag_len = srtp_auth_get_tag_length(stream->session_keys[0].rtp_auth);
  }

  if (tag_len > base_mki_start_location) {
     *mki_size = 0;
     return NULL;
  }

  base_mki_start_location -= tag_len;

  for (i = 0; i < stream->num_master_keys; i++) {
      if (stream->session_keys[i].mki_size != 0) {
          *mki_size = stream->session_keys[i].mki_size;
          mki_start_location = base_mki_start_location - *mki_size;

          if ( mki_start_location >= *mki_size &&
              memcmp(hdr + mki_start_location, stream->session_keys[i].mki_id, *mki_size) == 0 ) {
              return &stream->session_keys[i];
	  }
      }
  }

  *mki_size = 0;
  return NULL;
}

/*
 * This function handles outgoing SRTP packets while in AEAD mode,
 * which currently supports AES-GCM encryption.  All packets are
 * encrypted and authenticated.
 */
static srtp_err_status_t
srtp_protect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream,
                   void *rtp_hdr, unsigned int *pkt_octet_len,
                   srtp_session_keys_t *session_keys, unsigned int use_mki)
{
    srtp_hdr_t *hdr = (srtp_hdr_t*)rtp_hdr;
    uint32_t *enc_start;        /* pointer to start of encrypted portion  */
    int enc_octet_len = 0; /* number of octets in encrypted portion  */
    srtp_xtd_seq_num_t est;          /* estimated xtd_seq_num_t of *hdr        */
    int delta;                  /* delta of local pkt idx and that in hdr */
    srtp_err_status_t status;
    uint32_t tag_len;
    v128_t iv;
    unsigned int aad_len;
    srtp_hdr_xtnd_t *xtn_hdr = NULL;
    unsigned int mki_size = 0;
    uint8_t *mki_location = NULL;

    debug_print(mod_srtp, "function srtp_protect_aead", NULL);

    /*
     * update the key usage limit, and check it to make sure that we
     * didn't just hit either the soft limit or the hard limit, and call
     * the event handler if we hit either.
     */
    switch (srtp_key_limit_update(session_keys->limit)) {
    case srtp_key_event_normal:
        break;
    case srtp_key_event_hard_limit:
        srtp_handle_event(ctx, stream, event_key_hard_limit);
        return srtp_err_status_key_expired;
    case srtp_key_event_soft_limit:
    default:
        srtp_handle_event(ctx, stream, event_key_soft_limit);
        break;
    }

    /* get tag length from stream */
    tag_len = srtp_auth_get_tag_length(session_keys->rtp_auth);

    /*
     * find starting point for encryption and length of data to be
     * encrypted - the encrypted portion starts after the rtp header
     * extension, if present; otherwise, it starts after the last csrc,
     * if any are present
     */
     enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc;
     if (hdr->x == 1) {
         xtn_hdr = (srtp_hdr_xtnd_t*)enc_start;
         enc_start += (ntohs(xtn_hdr->length) + 1);
     }
     /* note: the passed size is without the auth tag */
     if (!((uint8_t*)enc_start <= (uint8_t*)hdr + *pkt_octet_len))
         return srtp_err_status_parse_err;
     enc_octet_len = (int)(*pkt_octet_len -
                                    ((uint8_t*)enc_start - (uint8_t*)hdr));
     if (enc_octet_len < 0) return srtp_err_status_parse_err;

    /*
     * estimate the packet index using the start of the replay window
     * and the sequence number from the header
     */
    delta = srtp_rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq));
    status = srtp_rdbx_check(&stream->rtp_rdbx, delta);
    if (status) {
	if (status != srtp_err_status_replay_fail || !stream->allow_repeat_tx) {
	    return status;  /* we've been asked to reuse an index */
	}
    } else {
	srtp_rdbx_add_index(&stream->rtp_rdbx, delta);
    }

#ifdef NO_64BIT_MATH
    debug_print2(mod_srtp, "estimated packet index: %08x%08x",
                 high32(est), low32(est));
#else
    debug_print(mod_srtp, "estimated packet index: %016llx", est);
#endif

    /*
     * AEAD uses a new IV formation method
     */
    srtp_calc_aead_iv(session_keys, &iv, &est, hdr);
    /* shift est, put into network byte order */
#ifdef NO_64BIT_MATH
    est = be64_to_cpu(make64((high32(est) << 16) |
                             (low32(est) >> 16),
                             low32(est) << 16));
#else
    est = be64_to_cpu(est << 16);
#endif

    status = srtp_cipher_set_iv(session_keys->rtp_cipher,
                                (uint8_t*)&iv, srtp_direction_encrypt);
    if (!status && session_keys->rtp_xtn_hdr_cipher) {
      iv.v32[0] = 0;
      iv.v32[1] = hdr->ssrc;
      iv.v64[1] = est;
      status = srtp_cipher_set_iv(session_keys->rtp_xtn_hdr_cipher,
                                  (uint8_t*)&iv, srtp_direction_encrypt);
    }
    if (status) {
        return srtp_err_status_cipher_fail;
    }

    if (xtn_hdr && session_keys->rtp_xtn_hdr_cipher) {
      /*
       * extensions header encryption RFC 6904
       */
	status = srtp_process_header_encryption(stream, xtn_hdr, session_keys);
      if (status) {
        return status;
      }
    }

    /*
     * Set the AAD over the RTP header 
     */
    aad_len = (uint8_t *)enc_start - (uint8_t *)hdr;
    status = srtp_cipher_set_aad(session_keys->rtp_cipher, (uint8_t*)hdr, aad_len);
    if (status) {
        return ( srtp_err_status_cipher_fail);
    }

    /* Encrypt the payload  */
    status = srtp_cipher_encrypt(session_keys->rtp_cipher,
                            (uint8_t*)enc_start, (unsigned int *)&enc_octet_len);
    if (status) {
        return srtp_err_status_cipher_fail;
    }
    /*
     * If we're doing GCM, we need to get the tag
     * and append that to the output
     */
    status = srtp_cipher_get_tag(session_keys->rtp_cipher, 
                            (uint8_t*)enc_start+enc_octet_len, &tag_len);
    if (status) {
	return ( srtp_err_status_cipher_fail);
    }

    mki_location = (uint8_t *)hdr + *pkt_octet_len + tag_len;
    mki_size = srtp_inject_mki(mki_location, session_keys, use_mki);

    /* increase the packet length by the length of the auth tag */
    *pkt_octet_len += tag_len;

    /* increase the packet length by the length of the mki_size */
    *pkt_octet_len += mki_size;

    return srtp_err_status_ok;
}


/*
 * This function handles incoming SRTP packets while in AEAD mode,
 * which currently supports AES-GCM encryption.  All packets are
 * encrypted and authenticated.  Note, the auth tag is at the end
 * of the packet stream and is automatically checked by GCM
 * when decrypting the payload.
 */
static srtp_err_status_t
srtp_unprotect_aead (srtp_ctx_t *ctx, srtp_stream_ctx_t *stream, int delta, 
                     srtp_xtd_seq_num_t est, void *srtp_hdr, unsigned int *pkt_octet_len,
                     srtp_session_keys_t *session_keys, unsigned int mki_size)
{
    srtp_hdr_t *hdr = (srtp_hdr_t*)srtp_hdr;
    uint32_t *enc_start;        /* pointer to start of encrypted portion  */
    unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */
    v128_t iv;
    srtp_err_status_t status;
    int tag_len;
    unsigned int aad_len;
    srtp_hdr_xtnd_t *xtn_hdr = NULL;

    debug_print(mod_srtp, "function srtp_unprotect_aead", NULL);

#ifdef NO_64BIT_MATH
    debug_print2(mod_srtp, "estimated u_packet index: %08x%08x", high32(est), low32(est));
#else
    debug_print(mod_srtp, "estimated u_packet index: %016llx", est);
#endif

    /* get tag length from stream */
    tag_len = srtp_auth_get_tag_length(session_keys->rtp_auth);

    /*
     * AEAD uses a new IV formation method 
     */
    srtp_calc_aead_iv(session_keys, &iv, &est, hdr);
    status = srtp_cipher_set_iv(session_keys->rtp_cipher,
                                (uint8_t*)&iv, srtp_direction_decrypt);
    if (!status && session_keys->rtp_xtn_hdr_cipher) {
      iv.v32[0] = 0;
      iv.v32[1] = hdr->ssrc;
#ifdef NO_64BIT_MATH
      iv.v64[1] = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16),
                  low32(est) << 16));
#else
      iv.v64[1] = be64_to_cpu(est << 16);
#endif
      status = srtp_cipher_set_iv(session_keys->rtp_xtn_hdr_cipher, (uint8_t*)&iv, srtp_direction_encrypt);
    }
    if (status) {
        return srtp_err_status_cipher_fail;
    }

    /*
     * find starting point for decryption and length of data to be
     * decrypted - the encrypted portion starts after the rtp header
     * extension, if present; otherwise, it starts after the last csrc,
     * if any are present
     */
    enc_start = (uint32_t*)hdr + uint32s_in_rtp_header + hdr->cc;
    if (hdr->x == 1) {
        xtn_hdr = (srtp_hdr_xtnd_t*)enc_start;
        enc_start += (ntohs(xtn_hdr->length) + 1);
    }
    if (!((uint8_t*)enc_start <= (uint8_t*)hdr + (*pkt_octet_len - tag_len - mki_size)))
        return srtp_err_status_parse_err;
    /*
     * We pass the tag down to the cipher when doing GCM mode 
     */
    enc_octet_len = (unsigned int)(*pkt_octet_len - mki_size -
                                   ((uint8_t*)enc_start - (uint8_t*)hdr));

    /*
     * Sanity check the encrypted payload length against
     * the tag size.  It must always be at least as large
     * as the tag length.
     */
    if (enc_octet_len < (unsigned int) tag_len) {
        return srtp_err_status_cipher_fail;
    }

    /*
     * update the key usage limit, and check it to make sure that we
     * didn't just hit either the soft limit or the hard limit, and call
     * the event handler if we hit either.
     */
    switch (srtp_key_limit_update(session_keys->limit)) {
    case srtp_key_event_normal:
        break;
    case srtp_key_event_soft_limit:
        srtp_handle_event(ctx, stream, event_key_soft_limit);
        break;
    case srtp_key_event_hard_limit:
        srtp_handle_event(ctx, stream, event_key_hard_limit);
        return srtp_err_status_key_expired;
    default:
        break;
    }

    /*
     * Set the AAD for AES-GCM, which is the RTP header
     */
    aad_len = (uint8_t *)enc_start - (uint8_t *)hdr;
    status = srtp_cipher_set_aad(session_keys->rtp_cipher, (uint8_t*)hdr, aad_len);
    if (status) {
        return ( srtp_err_status_cipher_fail);
    }

    /* Decrypt the ciphertext.  This also checks the auth tag based
     * on the AAD we just specified above */
    status = srtp_cipher_decrypt(session_keys->rtp_cipher,
                                 (uint8_t*)enc_start, &enc_octet_len);
    if (status) {
        return status;
    }

    if (xtn_hdr && session_keys->rtp_xtn_hdr_cipher) {
      /*
       * extensions header encryption RFC 6904
       */
      status = srtp_process_header_encryption(stream, xtn_hdr, session_keys);
      if (status) {
        return status;
      }
    }

    /*
     * verify that stream is for received traffic - this check will
     * detect SSRC collisions, since a stream that appears in both
     * srtp_protect() and srtp_unprotect() will fail this test in one of
     * those functions.
     *
     * we do this check *after* the authentication check, so that the
     * latter check will catch any attempts to fool us into thinking
     * that we've got a collision
     */
    if (stream->direction != dir_srtp_receiver) {
        if (stream->direction == dir_unknown) {
            stream->direction = dir_srtp_receiver;
        } else {
            srtp_handle_event(ctx, stream, event_ssrc_collision);
        }
    }

    /*
     * if the stream is a 'provisional' one, in which the template context
     * is used, then we need to allocate a new stream at this point, since
     * the authentication passed
     */
    if (stream == ctx->stream_template) {
        srtp_stream_ctx_t *new_stream;

        /*
         * allocate and initialize a new stream
         *
         * note that we indicate failure if we can't allocate the new
         * stream, and some implementations will want to not return
         * failure here
         */
        status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream);
        if (status) {
            return status;
        }

        /* add new stream to the head of the stream_list */
        new_stream->next = ctx->stream_list;
        ctx->stream_list = new_stream;

        /* set stream (the pointer used in this function) */
        stream = new_stream;
    }

    /*
     * the message authentication function passed, so add the packet
     * index into the replay database
     */
    srtp_rdbx_add_index(&stream->rtp_rdbx, delta);

    /* decrease the packet length by the length of the auth tag */
    *pkt_octet_len -= tag_len;

    /* decrease the packet length by the length of the mki_size */
    *pkt_octet_len -= mki_size;

    return srtp_err_status_ok;
}


 srtp_err_status_t
 srtp_protect(srtp_ctx_t *ctx, void *rtp_hdr, int *pkt_octet_len) {
   return srtp_protect_mki(ctx, rtp_hdr, pkt_octet_len, 0, 0);
 }

srtp_err_status_t
srtp_protect_mki(srtp_ctx_t *ctx, void *rtp_hdr, int *pkt_octet_len,
                 unsigned int use_mki, unsigned int mki_index ) {
   srtp_hdr_t *hdr = (srtp_hdr_t *)rtp_hdr;
   uint32_t *enc_start;        /* pointer to start of encrypted portion  */
   uint32_t *auth_start;       /* pointer to start of auth. portion      */
   int enc_octet_len = 0; /* number of octets in encrypted portion  */
   srtp_xtd_seq_num_t est;          /* estimated xtd_seq_num_t of *hdr        */
   int delta;                  /* delta of local pkt idx and that in hdr */
   uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
   srtp_err_status_t status;   
   int tag_len;
   srtp_stream_ctx_t *stream;
   uint32_t prefix_len;
   srtp_hdr_xtnd_t *xtn_hdr = NULL;
   unsigned int mki_size = 0;
   srtp_session_keys_t *session_keys = NULL;
   uint8_t* mki_location = NULL;

   debug_print(mod_srtp, "function srtp_protect", NULL);

  /* we assume the hdr is 32-bit aligned to start */

  /* Verify RTP header */
  status = srtp_validate_rtp_header(rtp_hdr, pkt_octet_len);
  if (status)
    return status;

   /* check the packet length - it must at least contain a full header */
   if (*pkt_octet_len < octets_in_rtp_header)
     return srtp_err_status_bad_param;

   /*
    * look up ssrc in srtp_stream list, and process the packet with
    * the appropriate stream.  if we haven't seen this stream before,
    * there's a template key for this srtp_session, and the cipher
    * supports key-sharing, then we assume that a new stream using
    * that key has just started up
    */
   stream = srtp_get_stream(ctx, hdr->ssrc);
   if (stream == NULL) {
     if (ctx->stream_template != NULL) {
       srtp_stream_ctx_t *new_stream;

       /* allocate and initialize a new stream */
       status = srtp_stream_clone(ctx->stream_template, 
				  hdr->ssrc, &new_stream); 
       if (status)
	 return status;

       /* add new stream to the head of the stream_list */
       new_stream->next = ctx->stream_list;
       ctx->stream_list = new_stream;

       /* set direction to outbound */
       new_stream->direction = dir_srtp_sender;

       /* set stream (the pointer used in this function) */
       stream = new_stream;
     } else {
       /* no template stream, so we return an error */
       return srtp_err_status_no_ctx;
     } 
   }

   /* 
    * verify that stream is for sending traffic - this check will
    * detect SSRC collisions, since a stream that appears in both
    * srtp_protect() and srtp_unprotect() will fail this test in one of
    * those functions.
    */

  if (stream->direction != dir_srtp_sender) {
     if (stream->direction == dir_unknown) {
       stream->direction = dir_srtp_sender;
     } else {
       srtp_handle_event(ctx, stream, event_ssrc_collision);
     }
  }

  session_keys = srtp_get_session_keys_with_mki_index(stream, use_mki, mki_index);

   /*
    * Check if this is an AEAD stream (GCM mode).  If so, then dispatch
    * the request to our AEAD handler.
    */
  if (session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_128 ||
      session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_256) {
      return srtp_protect_aead(ctx, stream, rtp_hdr,
                               (unsigned int*)pkt_octet_len, session_keys,
                               use_mki);
  }

  /* 
   * update the key usage limit, and check it to make sure that we
   * didn't just hit either the soft limit or the hard limit, and call
   * the event handler if we hit either.
   */
  switch(srtp_key_limit_update(session_keys->limit)) {
  case srtp_key_event_normal:
    break;
  case srtp_key_event_soft_limit: 
    srtp_handle_event(ctx, stream, event_key_soft_limit);
    break; 
  case srtp_key_event_hard_limit:
    srtp_handle_event(ctx, stream, event_key_hard_limit);
	return srtp_err_status_key_expired;
  default:
    break;
  }

   /* get tag length from stream */
   tag_len = srtp_auth_get_tag_length(session_keys->rtp_auth); 

   /*
    * find starting point for encryption and length of data to be
    * encrypted - the encrypted portion starts after the rtp header
    * extension, if present; otherwise, it starts after the last csrc,
    * if any are present
    *
    * if we're not providing confidentiality, set enc_start to NULL
    */
   if (stream->rtp_services & sec_serv_conf) {
     enc_start = (uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc;  
     if (hdr->x == 1) {
       xtn_hdr = (srtp_hdr_xtnd_t *)enc_start;
       enc_start += (ntohs(xtn_hdr->length) + 1);
     }
     /* note: the passed size is without the auth tag */
     if (!((uint8_t*)enc_start <= (uint8_t*)hdr + *pkt_octet_len))
       return srtp_err_status_parse_err;
     enc_octet_len = (int)(*pkt_octet_len -
                                    ((uint8_t*)enc_start - (uint8_t*)hdr));
     if (enc_octet_len < 0) return srtp_err_status_parse_err;
   } else {
     enc_start = NULL;
   }

   mki_location = (uint8_t *)hdr + *pkt_octet_len;
   mki_size = srtp_inject_mki(mki_location, session_keys, use_mki);

   /* 
    * if we're providing authentication, set the auth_start and auth_tag
    * pointers to the proper locations; otherwise, set auth_start to NULL
    * to indicate that no authentication is needed
    */
   if (stream->rtp_services & sec_serv_auth) {
     auth_start = (uint32_t *)hdr;
     auth_tag = (uint8_t *)hdr + *pkt_octet_len + mki_size;
   } else {
     auth_start = NULL;
     auth_tag = NULL;
   }

   /*
    * estimate the packet index using the start of the replay window   
    * and the sequence number from the header
    */
   delta = srtp_rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq));
   status = srtp_rdbx_check(&stream->rtp_rdbx, delta);
   if (status) {
     if (status != srtp_err_status_replay_fail || !stream->allow_repeat_tx)
       return status;  /* we've been asked to reuse an index */
   }
   else
     srtp_rdbx_add_index(&stream->rtp_rdbx, delta);

#ifdef NO_64BIT_MATH
   debug_print2(mod_srtp, "estimated packet index: %08x%08x", 
		high32(est),low32(est));
#else
   debug_print(mod_srtp, "estimated packet index: %016llx", est);
#endif

   /* 
    * if we're using rindael counter mode, set nonce and seq 
    */
   if (session_keys->rtp_cipher->type->id == SRTP_AES_ICM_128 ||
       session_keys->rtp_cipher->type->id == SRTP_AES_ICM_192 ||
       session_keys->rtp_cipher->type->id == SRTP_AES_ICM_256) {
     v128_t iv;

     iv.v32[0] = 0;
     iv.v32[1] = hdr->ssrc;
#ifdef NO_64BIT_MATH
     iv.v64[1] = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16),
								 low32(est) << 16));
#else
     iv.v64[1] = be64_to_cpu(est << 16);
#endif
     status = srtp_cipher_set_iv(session_keys->rtp_cipher, (uint8_t*)&iv, srtp_direction_encrypt);
     if (!status && session_keys->rtp_xtn_hdr_cipher) {
       status = srtp_cipher_set_iv(session_keys->rtp_xtn_hdr_cipher, (uint8_t*)&iv, srtp_direction_encrypt);
     }
   } else {  
     v128_t iv;

     /* otherwise, set the index to est */  
#ifdef NO_64BIT_MATH
     iv.v32[0] = 0;
     iv.v32[1] = 0;
#else
     iv.v64[0] = 0;
#endif
     iv.v64[1] = be64_to_cpu(est);
     status = srtp_cipher_set_iv(session_keys->rtp_cipher, (uint8_t*)&iv, srtp_direction_encrypt);
     if (!status && session_keys->rtp_xtn_hdr_cipher) {
       status = srtp_cipher_set_iv(session_keys->rtp_xtn_hdr_cipher, (uint8_t*)&iv, srtp_direction_encrypt);
     }
   }
   if (status)
     return srtp_err_status_cipher_fail;

   /* shift est, put into network byte order */
#ifdef NO_64BIT_MATH
   est = be64_to_cpu(make64((high32(est) << 16) |
						 (low32(est) >> 16),
						 low32(est) << 16));
#else
   est = be64_to_cpu(est << 16);
#endif
   
   /* 
    * if we're authenticating using a universal hash, put the keystream
    * prefix into the authentication tag
    */
   if (auth_start) {
     
    prefix_len = srtp_auth_get_prefix_length(session_keys->rtp_auth);    
    if (prefix_len) {
      status = srtp_cipher_output(session_keys->rtp_cipher, auth_tag, &prefix_len);
      if (status)
	return srtp_err_status_cipher_fail;
      debug_print(mod_srtp, "keystream prefix: %s", 
		  srtp_octet_string_hex_string(auth_tag, prefix_len));
    }
  }

  if (xtn_hdr && session_keys->rtp_xtn_hdr_cipher) {
    /*
     * extensions header encryption RFC 6904
     */
      status = srtp_process_header_encryption(stream, xtn_hdr, session_keys);
    if (status) {
      return status;
    }
  }

  /* if we're encrypting, exor keystream into the message */
  if (enc_start) {
    status = srtp_cipher_encrypt(session_keys->rtp_cipher, 
			        (uint8_t *)enc_start, (unsigned int *)&enc_octet_len);
    if (status)
      return srtp_err_status_cipher_fail;
  }

  /*
   *  if we're authenticating, run authentication function and put result
   *  into the auth_tag 
   */
  if (auth_start) {        

    /* initialize auth func context */
    status = srtp_auth_start(session_keys->rtp_auth);
    if (status) return status;

    /* run auth func over packet */
    status = srtp_auth_update(session_keys->rtp_auth,
			 (uint8_t *)auth_start, *pkt_octet_len);
    if (status) return status;
    
    /* run auth func over ROC, put result into auth_tag */
    debug_print(mod_srtp, "estimated packet index: %016llx", est);
    status = srtp_auth_compute(session_keys->rtp_auth, (uint8_t *)&est, 4, auth_tag);
    debug_print(mod_srtp, "srtp auth tag:    %s", 
		srtp_octet_string_hex_string(auth_tag, tag_len));
    if (status)
      return srtp_err_status_auth_fail;   

  }

  if (auth_tag) {

    /* increase the packet length by the length of the auth tag */
    *pkt_octet_len += tag_len;
  }

  if (use_mki) {
    /* increate the packet length by the mki size */
    *pkt_octet_len += mki_size;
  }

  return srtp_err_status_ok;  
}


srtp_err_status_t
srtp_unprotect(srtp_ctx_t *ctx, void *srtp_hdr, int *pkt_octet_len) {
    return srtp_unprotect_mki(ctx, srtp_hdr, pkt_octet_len, 0);
}

srtp_err_status_t
srtp_unprotect_mki(srtp_ctx_t *ctx, void *srtp_hdr, int *pkt_octet_len,
                   unsigned int use_mki) {
  srtp_hdr_t *hdr = (srtp_hdr_t *)srtp_hdr;
  uint32_t *enc_start;      /* pointer to start of encrypted portion  */
  uint32_t *auth_start;     /* pointer to start of auth. portion      */
  unsigned int enc_octet_len = 0;/* number of octets in encrypted portion */
  uint8_t *auth_tag = NULL; /* location of auth_tag within packet     */
  srtp_xtd_seq_num_t est;        /* estimated xtd_seq_num_t of *hdr        */
  int delta;                /* delta of local pkt idx and that in hdr */
  v128_t iv;
  srtp_err_status_t status;
  srtp_stream_ctx_t *stream;
  uint8_t tmp_tag[SRTP_MAX_TAG_LEN];
  uint32_t tag_len, prefix_len;
  srtp_hdr_xtnd_t *xtn_hdr = NULL;
  unsigned int mki_size = 0;
  srtp_session_keys_t *session_keys = NULL;

  debug_print(mod_srtp, "function srtp_unprotect", NULL);

  /* we assume the hdr is 32-bit aligned to start */

  /* Verify RTP header */
  status = srtp_validate_rtp_header(srtp_hdr, pkt_octet_len);
  if (status)
    return status;

  /* check the packet length - it must at least contain a full header */
  if (*pkt_octet_len < octets_in_rtp_header)
    return srtp_err_status_bad_param;

  /*
   * look up ssrc in srtp_stream list, and process the packet with 
   * the appropriate stream.  if we haven't seen this stream before,
   * there's only one key for this srtp_session, and the cipher
   * supports key-sharing, then we assume that a new stream using
   * that key has just started up
   */
  stream = srtp_get_stream(ctx, hdr->ssrc);
  if (stream == NULL) {
    if (ctx->stream_template != NULL) {
      stream = ctx->stream_template;
      debug_print(mod_srtp, "using provisional stream (SSRC: 0x%08x)",
		  ntohl(hdr->ssrc));
      
      /* 
       * set estimated packet index to sequence number from header,
       * and set delta equal to the same value
       */
#ifdef NO_64BIT_MATH
      est = (srtp_xtd_seq_num_t) make64(0,ntohs(hdr->seq));
      delta = low32(est);
#else
      est = (srtp_xtd_seq_num_t) ntohs(hdr->seq);
      delta = (int)est;
#endif
    } else {
      
      /*
       * no stream corresponding to SSRC found, and we don't do
       * key-sharing, so return an error
       */
      return srtp_err_status_no_ctx;
    }
  } else {
  
    /* estimate packet index from seq. num. in header */
    delta = srtp_rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq));
    
    /* check replay database */
    status = srtp_rdbx_check(&stream->rtp_rdbx, delta);
    if (status)
      return status;
  }

#ifdef NO_64BIT_MATH
  debug_print2(mod_srtp, "estimated u_packet index: %08x%08x", high32(est),low32(est));
#else
  debug_print(mod_srtp, "estimated u_packet index: %016llx", est);
#endif

  /*
   * Determine if MKI is being used and what session keys should be used
   */
  if (use_mki) {
      session_keys = srtp_get_session_keys(stream, (uint8_t *)hdr,
                                           (const unsigned int*)pkt_octet_len,
                                           &mki_size);

      if (session_keys == NULL) 
         return srtp_err_status_bad_mki;
  } else {
      session_keys = &stream->session_keys[0];
  }

  /*
   * Check if this is an AEAD stream (GCM mode).  If so, then dispatch
   * the request to our AEAD handler.
   */
  if (session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_128 ||
      session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_256) {
      return srtp_unprotect_aead(ctx, stream, delta, est, srtp_hdr,
                                 (unsigned int*)pkt_octet_len, session_keys,
                                 mki_size);
  }

  /* get tag length from stream */
  tag_len = srtp_auth_get_tag_length(session_keys->rtp_auth); 

  /* 
   * set the cipher's IV properly, depending on whatever cipher we
   * happen to be using
   */
  if (session_keys->rtp_cipher->type->id == SRTP_AES_ICM_128 ||
      session_keys->rtp_cipher->type->id == SRTP_AES_ICM_192 ||
      session_keys->rtp_cipher->type->id == SRTP_AES_ICM_256) {
    /* aes counter mode */
    iv.v32[0] = 0;
    iv.v32[1] = hdr->ssrc;  /* still in network order */
#ifdef NO_64BIT_MATH
    iv.v64[1] = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16),
			         low32(est) << 16));
#else
    iv.v64[1] = be64_to_cpu(est << 16);
#endif
    status = srtp_cipher_set_iv(session_keys->rtp_cipher,
                                (uint8_t*)&iv, srtp_direction_decrypt);
    if (!status && session_keys->rtp_xtn_hdr_cipher) {
      status = srtp_cipher_set_iv(session_keys->rtp_xtn_hdr_cipher,
                                  (uint8_t*)&iv, srtp_direction_decrypt);
    }
  } else {  
    
    /* no particular format - set the iv to the pakcet index */  
#ifdef NO_64BIT_MATH
    iv.v32[0] = 0;
    iv.v32[1] = 0;
#else
    iv.v64[0] = 0;
#endif
    iv.v64[1] = be64_to_cpu(est);
    status = srtp_cipher_set_iv(session_keys->rtp_cipher, (uint8_t*)&iv, srtp_direction_decrypt);
    if (!status && session_keys->rtp_xtn_hdr_cipher) {
      status = srtp_cipher_set_iv(session_keys->rtp_xtn_hdr_cipher, (uint8_t*)&iv, srtp_direction_decrypt);
    }
  }
  if (status)
    return srtp_err_status_cipher_fail;

  /* shift est, put into network byte order */
#ifdef NO_64BIT_MATH
  est = be64_to_cpu(make64((high32(est) << 16) |
					    (low32(est) >> 16),
					    low32(est) << 16));
#else
  est = be64_to_cpu(est << 16);
#endif

  /*
   * find starting point for decryption and length of data to be
   * decrypted - the encrypted portion starts after the rtp header
   * extension, if present; otherwise, it starts after the last csrc,
   * if any are present
   *
   * if we're not providing confidentiality, set enc_start to NULL
   */
  if (stream->rtp_services & sec_serv_conf) {
    enc_start = (uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc;  
    if (hdr->x == 1) {
      xtn_hdr = (srtp_hdr_xtnd_t *)enc_start;
      enc_start += (ntohs(xtn_hdr->length) + 1);
    }  
    if (!((uint8_t*)enc_start <= (uint8_t*)hdr + (*pkt_octet_len - tag_len - mki_size)))
      return srtp_err_status_parse_err;
    enc_octet_len = (uint32_t)(*pkt_octet_len - tag_len - mki_size -
                               ((uint8_t*)enc_start - (uint8_t*)hdr));
  } else {
    enc_start = NULL;
  }

  /* 
   * if we're providing authentication, set the auth_start and auth_tag
   * pointers to the proper locations; otherwise, set auth_start to NULL
   * to indicate that no authentication is needed
   */
  if (stream->rtp_services & sec_serv_auth) {
    auth_start = (uint32_t *)hdr;
    auth_tag = (uint8_t *)hdr + *pkt_octet_len - tag_len;
  } else {
    auth_start = NULL;
    auth_tag = NULL;
  } 

  /*
   * if we expect message authentication, run the authentication
   * function and compare the result with the value of the auth_tag
   */
  if (auth_start) {        

    /* 
     * if we're using a universal hash, then we need to compute the
     * keystream prefix for encrypting the universal hash output
     *
     * if the keystream prefix length is zero, then we know that
     * the authenticator isn't using a universal hash function
     */  
    if (session_keys->rtp_auth->prefix_len != 0) {
      
      prefix_len = srtp_auth_get_prefix_length(session_keys->rtp_auth);    
      status = srtp_cipher_output(session_keys->rtp_cipher, tmp_tag, &prefix_len);
      debug_print(mod_srtp, "keystream prefix: %s", 
		  srtp_octet_string_hex_string(tmp_tag, prefix_len));
      if (status)
	return srtp_err_status_cipher_fail;
    } 

    /* initialize auth func context */
    status = srtp_auth_start(session_keys->rtp_auth);
    if (status) return status;
 
    /* now compute auth function over packet */
    status = srtp_auth_update(session_keys->rtp_auth, (uint8_t *)auth_start,
			 *pkt_octet_len - tag_len - mki_size);

    /* run auth func over ROC, then write tmp tag */
    status = srtp_auth_compute(session_keys->rtp_auth, (uint8_t *)&est, 4, tmp_tag);

    debug_print(mod_srtp, "computed auth tag:    %s", 
		srtp_octet_string_hex_string(tmp_tag, tag_len));
    debug_print(mod_srtp, "packet auth tag:      %s", 
		srtp_octet_string_hex_string(auth_tag, tag_len));
    if (status)
      return srtp_err_status_auth_fail;   

    if (octet_string_is_eq(tmp_tag, auth_tag, tag_len))
      return srtp_err_status_auth_fail;
  }

  /* 
   * update the key usage limit, and check it to make sure that we
   * didn't just hit either the soft limit or the hard limit, and call
   * the event handler if we hit either.
   */
  switch(srtp_key_limit_update(session_keys->limit)) {
  case srtp_key_event_normal:
    break;
  case srtp_key_event_soft_limit: 
    srtp_handle_event(ctx, stream, event_key_soft_limit);
    break; 
  case srtp_key_event_hard_limit:
    srtp_handle_event(ctx, stream, event_key_hard_limit);
    return srtp_err_status_key_expired;
  default:
    break;
  }

  if (xtn_hdr && session_keys->rtp_xtn_hdr_cipher) {
    /*
     * extensions header encryption RFC 6904
     */
      status = srtp_process_header_encryption(stream, xtn_hdr, session_keys);
    if (status) {
      return status;
    }
  }

  /* if we're decrypting, add keystream into ciphertext */
  if (enc_start) {
    status = srtp_cipher_decrypt(session_keys->rtp_cipher,
                                 (uint8_t *)enc_start, &enc_octet_len);
    if (status)
      return srtp_err_status_cipher_fail;
  }

  /* 
   * verify that stream is for received traffic - this check will
   * detect SSRC collisions, since a stream that appears in both
   * srtp_protect() and srtp_unprotect() will fail this test in one of
   * those functions.
   *
   * we do this check *after* the authentication check, so that the
   * latter check will catch any attempts to fool us into thinking
   * that we've got a collision
   */
  if (stream->direction != dir_srtp_receiver) {
    if (stream->direction == dir_unknown) {
      stream->direction = dir_srtp_receiver;
    } else {
      srtp_handle_event(ctx, stream, event_ssrc_collision);
    }
  }

  /* 
   * if the stream is a 'provisional' one, in which the template context
   * is used, then we need to allocate a new stream at this point, since
   * the authentication passed
   */
  if (stream == ctx->stream_template) {  
    srtp_stream_ctx_t *new_stream;

    /* 
     * allocate and initialize a new stream 
     * 
     * note that we indicate failure if we can't allocate the new
     * stream, and some implementations will want to not return
     * failure here
     */
    status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream); 
    if (status)
      return status;
    
    /* add new stream to the head of the stream_list */
    new_stream->next = ctx->stream_list;
    ctx->stream_list = new_stream;
    
    /* set stream (the pointer used in this function) */
    stream = new_stream;
  }
  
  /* 
   * the message authentication function passed, so add the packet
   * index into the replay database 
   */
  srtp_rdbx_add_index(&stream->rtp_rdbx, delta);

  /* decrease the packet length by the length of the auth tag */
  *pkt_octet_len -= tag_len;

  /* decrease the packet length by the mki size */
  *pkt_octet_len -= mki_size;

  return srtp_err_status_ok;  
}

srtp_err_status_t
srtp_init() {
  srtp_err_status_t status;

  /* initialize crypto kernel */
  status = srtp_crypto_kernel_init();
  if (status) 
    return status;

  /* load srtp debug module into the kernel */
  status = srtp_crypto_kernel_load_debug_module(&mod_srtp);
  if (status)
    return status;

  return srtp_err_status_ok;
}

srtp_err_status_t
srtp_shutdown() {
  srtp_err_status_t status;

  /* shut down crypto kernel */
  status = srtp_crypto_kernel_shutdown();
  if (status) 
    return status;

  /* shutting down crypto kernel frees the srtp debug module as well */

  return srtp_err_status_ok;
}


/* 
 * The following code is under consideration for removal.  See
 * SRTP_MAX_TRAILER_LEN 
 */
#if 0

/*
 * srtp_get_trailer_length(&a) returns the number of octets that will
 * be added to an RTP packet by the SRTP processing.  This value
 * is constant for a given srtp_stream_t (i.e. between initializations).
 */

int
srtp_get_trailer_length(const srtp_stream_t s) {
  return srtp_auth_get_tag_length(s->rtp_auth);
}

#endif

/*
 * srtp_get_stream(ssrc) returns a pointer to the stream corresponding
 * to ssrc, or NULL if no stream exists for that ssrc
 *
 * this is an internal function 
 */

srtp_stream_ctx_t *
srtp_get_stream(srtp_t srtp, uint32_t ssrc) {
  srtp_stream_ctx_t *stream;

  /* walk down list until ssrc is found */
  stream = srtp->stream_list;
  while (stream != NULL) {
    if (stream->ssrc == ssrc)
      return stream;
    stream = stream->next;
  }
  
  /* we haven't found our ssrc, so return a null */
  return NULL;
}

srtp_err_status_t
srtp_dealloc(srtp_t session) {
  srtp_stream_ctx_t *stream;
  srtp_err_status_t status;

  /*
   * we take a conservative deallocation strategy - if we encounter an
   * error deallocating a stream, then we stop trying to deallocate
   * memory and just return an error
   */

  /* walk list of streams, deallocating as we go */
  stream = session->stream_list;
  while (stream != NULL) {
    srtp_stream_t next = stream->next;
    status = srtp_stream_dealloc(stream, session->stream_template);
    if (status)
      return status;
    stream = next;
  }
  
  /* deallocate stream template, if there is one */
  if (session->stream_template != NULL) {
    status = srtp_stream_dealloc(session->stream_template, NULL);
    if (status)
      return status;
  }

  /* deallocate session context */
  srtp_crypto_free(session);

  return srtp_err_status_ok;
}


srtp_err_status_t
srtp_add_stream(srtp_t session, 
		const srtp_policy_t *policy)  {
  srtp_err_status_t status;
  srtp_stream_t tmp;

  /* sanity check arguments */
  if ((session == NULL) || (policy == NULL) || (!srtp_validate_policy_master_keys(policy)))
    return srtp_err_status_bad_param;

  /* allocate stream  */
  status = srtp_stream_alloc(&tmp, policy);
  if (status) {
    return status;
  }
  
  /* initialize stream  */
  status = srtp_stream_init(tmp, policy);
  if (status) {
    srtp_crypto_free(tmp);
    return status;
  }
  
  /* 
   * set the head of the stream list or the template to point to the
   * stream that we've just alloced and init'ed, depending on whether
   * or not it has a wildcard SSRC value or not
   *
   * if the template stream has already been set, then the policy is
   * inconsistent, so we return a bad_param error code
   */
  switch (policy->ssrc.type) {
  case (ssrc_any_outbound):
    if (session->stream_template) {
      return srtp_err_status_bad_param;
    }
    session->stream_template = tmp;
    session->stream_template->direction = dir_srtp_sender;
    break;
  case (ssrc_any_inbound):
    if (session->stream_template) {
      return srtp_err_status_bad_param;
    }
    session->stream_template = tmp;
    session->stream_template->direction = dir_srtp_receiver;
    break;
  case (ssrc_specific):
    tmp->next = session->stream_list;
    session->stream_list = tmp;
    break;
  case (ssrc_undefined):
  default:
    srtp_crypto_free(tmp);
    return srtp_err_status_bad_param;
  }
    
  return srtp_err_status_ok;
}


srtp_err_status_t
srtp_create(srtp_t *session,               /* handle for session     */ 
	    const srtp_policy_t *policy) { /* SRTP policy (list)     */
  srtp_err_status_t stat;
  srtp_ctx_t *ctx;

  /* sanity check arguments */
  if (session == NULL)
    return srtp_err_status_bad_param;

  /* allocate srtp context and set ctx_ptr */
  ctx = (srtp_ctx_t *) srtp_crypto_alloc(sizeof(srtp_ctx_t));
  if (ctx == NULL)
    return srtp_err_status_alloc_fail;
  *session = ctx;

  /* 
   * loop over elements in the policy list, allocating and
   * initializing a stream for each element
   */
  ctx->stream_template = NULL;
  ctx->stream_list = NULL;
  ctx->user_data = NULL;
  while (policy != NULL) {    

    stat = srtp_add_stream(ctx, policy);
    if (stat) {
      /* clean up everything */
      srtp_dealloc(*session);
      *session = NULL;
      return stat;
    }    

    /* set policy to next item in list  */
    policy = policy->next;
  }

  return srtp_err_status_ok;
}


srtp_err_status_t
srtp_remove_stream(srtp_t session, uint32_t ssrc) {
  srtp_stream_ctx_t *stream, *last_stream;
  srtp_err_status_t status;

  /* sanity check arguments */
  if (session == NULL)
    return srtp_err_status_bad_param;
  
  /* find stream in list; complain if not found */
  last_stream = stream = session->stream_list;
  while ((stream != NULL) && (ssrc != stream->ssrc)) {
    last_stream = stream;
    stream = stream->next;
  }
  if (stream == NULL)
    return srtp_err_status_no_ctx;

  /* remove stream from the list */
  if (last_stream == stream)
    /* stream was first in list */
    session->stream_list = stream->next;
  else
    last_stream->next = stream->next;

  /* deallocate the stream */
  status = srtp_stream_dealloc(stream, session->stream_template);
  if (status)
    return status;

  return srtp_err_status_ok;
}


srtp_err_status_t
srtp_update(srtp_t session, const srtp_policy_t *policy) {
  srtp_err_status_t stat;

  /* sanity check arguments */
  if ((session == NULL) || (policy == NULL) || (!srtp_validate_policy_master_keys(policy))) {
    return srtp_err_status_bad_param;
  }

  while (policy != NULL) {
    stat = srtp_update_stream(session, policy);
    if (stat) {
      return stat;
    }

    /* set policy to next item in list  */
    policy = policy->next;
  }
  return srtp_err_status_ok;
}


static srtp_err_status_t
update_template_streams(srtp_t session, const srtp_policy_t *policy) {
  srtp_err_status_t status;
  srtp_stream_t new_stream_template;
  srtp_stream_t new_stream_list = NULL;

  if (session->stream_template == NULL) {
    return srtp_err_status_bad_param;
  }

  /* allocate new template stream  */
  status = srtp_stream_alloc(&new_stream_template, policy);
  if (status) {
    return status;
  }

  /* initialize new template stream  */
  status = srtp_stream_init(new_stream_template, policy);
  if (status) {
    srtp_crypto_free(new_stream_template);
    return status;
  }

  /* for all old templated streams */
  for (;;) {
    srtp_stream_t stream;
    uint32_t ssrc;
    srtp_xtd_seq_num_t old_index;
    srtp_rdb_t old_rtcp_rdb;

    stream = session->stream_list;
    while ((stream != NULL) &&
           (stream->session_keys[0].rtp_auth !=
            session->stream_template->session_keys[0].rtp_auth)) {
      stream = stream->next;
    }
    if (stream == NULL) {
      /* no more templated streams */
      break;
    }

    /* save old extendard seq */
    ssrc = stream->ssrc;
    old_index = stream->rtp_rdbx.index;
    old_rtcp_rdb = stream->rtcp_rdb;

    /* remove stream */
    status = srtp_remove_stream(session, ssrc);
    if (status) {
      /* free new allocations */
      while (new_stream_list != NULL) {
        srtp_stream_t next = new_stream_list->next;
        srtp_stream_dealloc(new_stream_list, new_stream_template);
        new_stream_list = next;
      }
      srtp_stream_dealloc(new_stream_template, NULL);
      return status;
    }

    /* allocate and initialize a new stream */
    status = srtp_stream_clone(new_stream_template, ssrc, &stream);
    if (status) {
      /* free new allocations */
      while (new_stream_list != NULL) {
        srtp_stream_t next = new_stream_list->next;
        srtp_stream_dealloc(new_stream_list, new_stream_template);
        new_stream_list = next;
      }
      srtp_stream_dealloc(new_stream_template, NULL);
      return status;
    }

    /* add new stream to the head of the new_stream_list */
    stream->next = new_stream_list;
    new_stream_list = stream;

    /* restore old extended seq */
    stream->rtp_rdbx.index = old_index;
    stream->rtcp_rdb = old_rtcp_rdb;
  }
  /* dealloc old template */
  srtp_stream_dealloc(session->stream_template, NULL);
  /* set new template */
  session->stream_template = new_stream_template;
  /* add new list */
  if (new_stream_list) {
    srtp_stream_t tail = new_stream_list;
    while (tail->next) {
      tail = tail->next;
    }
    tail->next = session->stream_list;
    session->stream_list = new_stream_list;
  }
  return status;
}


static srtp_err_status_t
update_stream(srtp_t session, const srtp_policy_t *policy) {
  srtp_err_status_t status;
  srtp_xtd_seq_num_t old_index;
  srtp_rdb_t old_rtcp_rdb;
  srtp_stream_t stream;

  stream = srtp_get_stream(session, htonl(policy->ssrc.value));
  if (stream == NULL) {
    return srtp_err_status_bad_param;
  }

  /* save old extendard seq */
  old_index = stream->rtp_rdbx.index;
  old_rtcp_rdb = stream->rtcp_rdb;

  status = srtp_remove_stream(session, htonl(policy->ssrc.value));
  if (status) {
    return status;
  }

  status = srtp_add_stream(session, policy);
  if (status) {
    return status;
  }

  stream = srtp_get_stream(session, htonl(policy->ssrc.value));
  if (stream == NULL) {
    return srtp_err_status_fail;
  }

  /* restore old extended seq */
  stream->rtp_rdbx.index = old_index;
  stream->rtcp_rdb = old_rtcp_rdb;

  return srtp_err_status_ok;
}


srtp_err_status_t
srtp_update_stream(srtp_t session, const srtp_policy_t *policy) {
  srtp_err_status_t status;

  /* sanity check arguments */
  if ((session == NULL) || (policy == NULL) || (!srtp_validate_policy_master_keys(policy)))
    return srtp_err_status_bad_param;

  switch (policy->ssrc.type) {
  case (ssrc_any_outbound):
  case (ssrc_any_inbound):
    status = update_template_streams(session, policy);
    break;
  case (ssrc_specific):
    status = update_stream(session, policy);
    break;
  case (ssrc_undefined):
  default:
    return srtp_err_status_bad_param;
  }

  return status;
}


/*
 * The default policy - provides a convenient way for callers to use
 * the default security policy
 *
 * The default policy is defined in RFC 3711
 * (Section 5. Default and mandatory-to-implement Transforms)
 *
 */

/* 
 * NOTE: cipher_key_len is really key len (128 bits) plus salt len
 *  (112 bits)
 */
/* There are hard-coded 16's for base_key_len in the key generation code */

void
srtp_crypto_policy_set_rtp_default(srtp_crypto_policy_t *p) {

  p->cipher_type     = SRTP_AES_ICM_128;
  p->cipher_key_len  = SRTP_AES_ICM_128_KEY_LEN_WSALT; /* default 128 bits per RFC 3711 */
  p->auth_type       = SRTP_HMAC_SHA1;             
  p->auth_key_len    = 20;                /* default 160 bits per RFC 3711 */
  p->auth_tag_len    = 10;                /* default 80 bits per RFC 3711 */
  p->sec_serv        = sec_serv_conf_and_auth;
  
}

void
srtp_crypto_policy_set_rtcp_default(srtp_crypto_policy_t *p) {

  p->cipher_type     = SRTP_AES_ICM_128;
  p->cipher_key_len  = SRTP_AES_ICM_128_KEY_LEN_WSALT; /* default 128 bits per RFC 3711 */
  p->auth_type       = SRTP_HMAC_SHA1;             
  p->auth_key_len    = 20;                 /* default 160 bits per RFC 3711 */
  p->auth_tag_len    = 10;                 /* default 80 bits per RFC 3711 */
  p->sec_serv        = sec_serv_conf_and_auth;
  
}

void
srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(srtp_crypto_policy_t *p) {

  /*
   * corresponds to RFC 4568
   *
   * note that this crypto policy is intended for SRTP, but not SRTCP
   */

  p->cipher_type     = SRTP_AES_ICM_128;
  p->cipher_key_len  = SRTP_AES_ICM_128_KEY_LEN_WSALT; /* 128 bit key, 112 bit salt */
  p->auth_type       = SRTP_HMAC_SHA1;             
  p->auth_key_len    = 20;                /* 160 bit key               */
  p->auth_tag_len    = 4;                 /* 32 bit tag                */
  p->sec_serv        = sec_serv_conf_and_auth;
  
}


void
srtp_crypto_policy_set_aes_cm_128_null_auth(srtp_crypto_policy_t *p) {

  /*
   * corresponds to RFC 4568
   *
   * note that this crypto policy is intended for SRTP, but not SRTCP
   */

  p->cipher_type     = SRTP_AES_ICM_128;
  p->cipher_key_len  = SRTP_AES_ICM_128_KEY_LEN_WSALT; /* 128 bit key, 112 bit salt */
  p->auth_type       = SRTP_NULL_AUTH;             
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 0; 
  p->sec_serv        = sec_serv_conf;
  
}


void
srtp_crypto_policy_set_null_cipher_hmac_sha1_80(srtp_crypto_policy_t *p) {

  /*
   * corresponds to RFC 4568
   */

  p->cipher_type     = SRTP_NULL_CIPHER;           
  p->cipher_key_len  = 0;
  p->auth_type       = SRTP_HMAC_SHA1;             
  p->auth_key_len    = 20; 
  p->auth_tag_len    = 10; 
  p->sec_serv        = sec_serv_auth;
  
}

void
srtp_crypto_policy_set_null_cipher_hmac_null(srtp_crypto_policy_t *p) {

  /*
   * Should only be used for testing
   */

  p->cipher_type     = SRTP_NULL_CIPHER;           
  p->cipher_key_len  = 0;
  p->auth_type       = SRTP_NULL_AUTH;             
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 0; 
  p->sec_serv        = sec_serv_none;
  
}


void
srtp_crypto_policy_set_aes_cm_256_hmac_sha1_80(srtp_crypto_policy_t *p) {

  /*
   * corresponds to RFC 6188
   */

  p->cipher_type     = SRTP_AES_ICM_256;
  p->cipher_key_len  = SRTP_AES_ICM_256_KEY_LEN_WSALT;
  p->auth_type       = SRTP_HMAC_SHA1;             
  p->auth_key_len    = 20;                /* default 160 bits per RFC 3711 */
  p->auth_tag_len    = 10;                /* default 80 bits per RFC 3711 */
  p->sec_serv        = sec_serv_conf_and_auth;
}


void
srtp_crypto_policy_set_aes_cm_256_hmac_sha1_32(srtp_crypto_policy_t *p) {

  /*
   * corresponds to RFC 6188
   *
   * note that this crypto policy is intended for SRTP, but not SRTCP
   */

  p->cipher_type     = SRTP_AES_ICM_256;
  p->cipher_key_len  = SRTP_AES_ICM_256_KEY_LEN_WSALT;
  p->auth_type       = SRTP_HMAC_SHA1;             
  p->auth_key_len    = 20;                /* default 160 bits per RFC 3711 */
  p->auth_tag_len    = 4;                 /* default 80 bits per RFC 3711 */
  p->sec_serv        = sec_serv_conf_and_auth;
}

/*
 * AES-256 with no authentication.
 */
void
srtp_crypto_policy_set_aes_cm_256_null_auth (srtp_crypto_policy_t *p)
{
    p->cipher_type     = SRTP_AES_ICM_256;
    p->cipher_key_len  = SRTP_AES_ICM_256_KEY_LEN_WSALT;
    p->auth_type       = SRTP_NULL_AUTH;
    p->auth_key_len    = 0;
    p->auth_tag_len    = 0;
    p->sec_serv        = sec_serv_conf;
}

#ifdef OPENSSL
void
srtp_crypto_policy_set_aes_cm_192_hmac_sha1_80(srtp_crypto_policy_t *p) {

  /*
   * corresponds to RFC 6188
   */

  p->cipher_type     = SRTP_AES_ICM_192;
  p->cipher_key_len  = SRTP_AES_ICM_192_KEY_LEN_WSALT;
  p->auth_type       = SRTP_HMAC_SHA1;
  p->auth_key_len    = 20;                /* default 160 bits per RFC 3711 */
  p->auth_tag_len    = 10;                /* default 80 bits per RFC 3711 */
  p->sec_serv        = sec_serv_conf_and_auth;
}


void
srtp_crypto_policy_set_aes_cm_192_hmac_sha1_32(srtp_crypto_policy_t *p) {

  /*
   * corresponds to RFC 6188
   *
   * note that this crypto policy is intended for SRTP, but not SRTCP
   */

  p->cipher_type     = SRTP_AES_ICM_192;
  p->cipher_key_len  = SRTP_AES_ICM_192_KEY_LEN_WSALT;
  p->auth_type       = SRTP_HMAC_SHA1;
  p->auth_key_len    = 20;                /* default 160 bits per RFC 3711 */
  p->auth_tag_len    = 4;                 /* default 80 bits per RFC 3711 */
  p->sec_serv        = sec_serv_conf_and_auth;
}

/*
 * AES-192 with no authentication.
 */
void
srtp_crypto_policy_set_aes_cm_192_null_auth (srtp_crypto_policy_t *p)
{
    p->cipher_type     = SRTP_AES_ICM_192;
    p->cipher_key_len  = SRTP_AES_ICM_192_KEY_LEN_WSALT;
    p->auth_type       = SRTP_NULL_AUTH;
    p->auth_key_len    = 0;
    p->auth_tag_len    = 0;
    p->sec_serv        = sec_serv_conf;
}

/*
 * AES-128 GCM mode with 8 octet auth tag. 
 */
void
srtp_crypto_policy_set_aes_gcm_128_8_auth(srtp_crypto_policy_t *p) {
  p->cipher_type     = SRTP_AES_GCM_128;
  p->cipher_key_len  = SRTP_AES_GCM_128_KEY_LEN_WSALT;
  p->auth_type       = SRTP_NULL_AUTH; /* GCM handles the auth for us */            
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 8;   /* 8 octet tag length */
  p->sec_serv        = sec_serv_conf_and_auth;
}

/*
 * AES-256 GCM mode with 8 octet auth tag. 
 */
void
srtp_crypto_policy_set_aes_gcm_256_8_auth(srtp_crypto_policy_t *p) {
  p->cipher_type     = SRTP_AES_GCM_256;
  p->cipher_key_len  = SRTP_AES_GCM_256_KEY_LEN_WSALT;
  p->auth_type       = SRTP_NULL_AUTH; /* GCM handles the auth for us */ 
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 8;   /* 8 octet tag length */
  p->sec_serv        = sec_serv_conf_and_auth;
}

/*
 * AES-128 GCM mode with 8 octet auth tag, no RTCP encryption. 
 */
void
srtp_crypto_policy_set_aes_gcm_128_8_only_auth(srtp_crypto_policy_t *p) {
  p->cipher_type     = SRTP_AES_GCM_128;
  p->cipher_key_len  = SRTP_AES_GCM_128_KEY_LEN_WSALT;
  p->auth_type       = SRTP_NULL_AUTH; /* GCM handles the auth for us */ 
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 8;   /* 8 octet tag length */
  p->sec_serv        = sec_serv_auth;  /* This only applies to RTCP */
}

/*
 * AES-256 GCM mode with 8 octet auth tag, no RTCP encryption. 
 */
void
srtp_crypto_policy_set_aes_gcm_256_8_only_auth(srtp_crypto_policy_t *p) {
  p->cipher_type     = SRTP_AES_GCM_256;
  p->cipher_key_len  = SRTP_AES_GCM_256_KEY_LEN_WSALT;
  p->auth_type       = SRTP_NULL_AUTH; /* GCM handles the auth for us */ 
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 8;   /* 8 octet tag length */
  p->sec_serv        = sec_serv_auth;  /* This only applies to RTCP */
}

/*
 * AES-128 GCM mode with 16 octet auth tag. 
 */
void
srtp_crypto_policy_set_aes_gcm_128_16_auth(srtp_crypto_policy_t *p) {
  p->cipher_type     = SRTP_AES_GCM_128;
  p->cipher_key_len  = SRTP_AES_GCM_128_KEY_LEN_WSALT;
  p->auth_type       = SRTP_NULL_AUTH; /* GCM handles the auth for us */            
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 16;   /* 16 octet tag length */
  p->sec_serv        = sec_serv_conf_and_auth;
}

/*
 * AES-256 GCM mode with 16 octet auth tag. 
 */
void
srtp_crypto_policy_set_aes_gcm_256_16_auth(srtp_crypto_policy_t *p) {
  p->cipher_type     = SRTP_AES_GCM_256;
  p->cipher_key_len  = SRTP_AES_GCM_256_KEY_LEN_WSALT;
  p->auth_type       = SRTP_NULL_AUTH; /* GCM handles the auth for us */ 
  p->auth_key_len    = 0; 
  p->auth_tag_len    = 16;   /* 16 octet tag length */
  p->sec_serv        = sec_serv_conf_and_auth;
}

#endif

/* 
 * secure rtcp functions
 */

/*
 * AEAD uses a new IV formation method.  This function implements
 * section 9.1 (SRTCP IV Formation for AES-GCM) from RFC7714.
 * The calculation is defined as, where (+) is the xor operation:
 *
 *                0  1  2  3  4  5  6  7  8  9 10 11
 *               +--+--+--+--+--+--+--+--+--+--+--+--+
 *               |00|00|    SSRC   |00|00|0+SRTCP Idx|---+
 *               +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *                                                       |
 *               +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *               |         Encryption Salt           |->(+)
 *               +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *                                                       |
 *               +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *               |       Initialization Vector       |<--+
 *               +--+--+--+--+--+--+--+--+--+--+--+--+*
 *
 * Input:  *session_keys - pointer to SRTP stream context session keys,
 *                        used to retrieve the SALT 
 *         *iv           - Pointer to recieve the calculated IV
 *         seq_num       - The SEQ value to use for the IV calculation.
 *         *hdr          - The RTP header, used to get the SSRC value
 *
 * Returns: srtp_err_status_ok if no error or srtp_err_status_bad_param
 *          if seq_num is invalid
 *
 */
static srtp_err_status_t
srtp_calc_aead_iv_srtcp(srtp_session_keys_t *session_keys, v128_t *iv,
                        uint32_t seq_num, srtcp_hdr_t *hdr)
{
    v128_t	in;
    v128_t	salt;

    memset(&in, 0, sizeof(v128_t));
    memset(&salt, 0, sizeof(v128_t));

    in.v16[0] = 0;
    memcpy(&in.v16[1], &hdr->ssrc, 4); /* still in network order! */
    in.v16[3] = 0;

    /*
     *  The SRTCP index (seq_num) spans bits 0 through 30 inclusive.
     *  The most significant bit should be zero.
     */
    if (seq_num & 0x80000000UL) {
        return srtp_err_status_bad_param;
    }
    in.v32[2] = htonl(seq_num);

    debug_print(mod_srtp, "Pre-salted RTCP IV = %s\n", v128_hex_string(&in));

    /*
     * Get the SALT value from the context
     */
    memcpy(salt.v8, session_keys->c_salt, 12);
    debug_print(mod_srtp, "RTCP SALT = %s\n", v128_hex_string(&salt));

    /*
     * Finally, apply the SALT to the input
     */
    v128_xor(iv, &in, &salt);

    return srtp_err_status_ok;
}

/*
 * This code handles AEAD ciphers for outgoing RTCP.  We currently support
 * AES-GCM mode with 128 or 256 bit keys. 
 */
static srtp_err_status_t
srtp_protect_rtcp_aead (srtp_t ctx, srtp_stream_ctx_t *stream, 
                        void *rtcp_hdr, unsigned int *pkt_octet_len,
                        srtp_session_keys_t *session_keys, unsigned int use_mki)
{
    srtcp_hdr_t *hdr = (srtcp_hdr_t*)rtcp_hdr;
    uint32_t *enc_start;        /* pointer to start of encrypted portion  */
    uint32_t *trailer;          /* pointer to start of trailer            */
    unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */
    uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
    srtp_err_status_t status;
    uint32_t tag_len;
    uint32_t seq_num;
    v128_t iv;
    uint32_t tseq;
    unsigned int mki_size = 0;

    /* get tag length from stream context */
    tag_len = srtp_auth_get_tag_length(session_keys->rtcp_auth);

    /*
     * set encryption start and encryption length - if we're not
     * providing confidentiality, set enc_start to NULL
     */
    enc_start = (uint32_t*)hdr + uint32s_in_rtcp_header;
    enc_octet_len = *pkt_octet_len - octets_in_rtcp_header;

    /* NOTE: hdr->length is not usable - it refers to only the first
           RTCP report in the compound packet! */
    /* NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
           multiples of 32-bits (RFC 3550 6.1) */
    trailer = (uint32_t*)((char*)enc_start + enc_octet_len + tag_len);

    if (stream->rtcp_services & sec_serv_conf) {
        *trailer = htonl(SRTCP_E_BIT); /* set encrypt bit */
    } else {
        enc_start = NULL;
        enc_octet_len = 0;
        /* 0 is network-order independant */
        *trailer = 0x00000000; /* set encrypt bit */
    }

    mki_size = srtp_inject_mki((uint8_t *)hdr + *pkt_octet_len + tag_len + sizeof(srtcp_trailer_t),
                               session_keys, use_mki);

    /*
     * set the auth_tag pointer to the proper location, which is after
     * the payload, but before the trailer
     * (note that srtpc *always* provides authentication, unlike srtp)
     */
    /* Note: This would need to change for optional mikey data */
    auth_tag = (uint8_t*)hdr + *pkt_octet_len;

    /*
     * check sequence number for overruns, and copy it into the packet
     * if its value isn't too big
     */
    status = srtp_rdb_increment(&stream->rtcp_rdb);
    if (status) {
        return status;
    }
    seq_num = srtp_rdb_get_value(&stream->rtcp_rdb);
    *trailer |= htonl(seq_num);
    debug_print(mod_srtp, "srtcp index: %x", seq_num);

    /*
     * Calculate and set the IV
     */
    status = srtp_calc_aead_iv_srtcp(session_keys, &iv, seq_num, hdr);
    if (status) {
        return srtp_err_status_cipher_fail;
    }
    status = srtp_cipher_set_iv(session_keys->rtcp_cipher,
                                (uint8_t*)&iv, srtp_direction_encrypt);
    if (status) {
        return srtp_err_status_cipher_fail;
    }

    /*
     * Set the AAD for GCM mode
     */
    if (enc_start) {
        /*
         * If payload encryption is enabled, then the AAD consist of
         * the RTCP header and the seq# at the end of the packet
         */
        status = srtp_cipher_set_aad(session_keys->rtcp_cipher,
                                 (uint8_t*)hdr, octets_in_rtcp_header);
        if (status) {
            return ( srtp_err_status_cipher_fail);
        }
    } else {
        /*
         * Since payload encryption is not enabled, we must authenticate
         * the entire packet as described in RFC 7714 (Section 9.3. Data
         * Types in Unencrypted SRTCP Compound Packets)
         */
        status = srtp_cipher_set_aad(session_keys->rtcp_cipher,
                                 (uint8_t*)hdr, *pkt_octet_len);
        if (status) {
            return ( srtp_err_status_cipher_fail);
        }
    }
    /*
     * Process the sequence# as AAD
     */
    tseq = *trailer;
    status = srtp_cipher_set_aad(session_keys->rtcp_cipher, (uint8_t*)&tseq,
                                 sizeof(srtcp_trailer_t));
    if (status) {
        return ( srtp_err_status_cipher_fail);
    }

    /* if we're encrypting, exor keystream into the message */
    if (enc_start) {
        status = srtp_cipher_encrypt(session_keys->rtcp_cipher,
                                     (uint8_t*)enc_start, &enc_octet_len);
        if (status) {
            return srtp_err_status_cipher_fail;
        }
        /*
         * Get the tag and append that to the output
         */
        status = srtp_cipher_get_tag(session_keys->rtcp_cipher, (uint8_t*)auth_tag,
                                     &tag_len);
        if (status) {
            return ( srtp_err_status_cipher_fail);
        }
        enc_octet_len += tag_len;
    } else {
        /*
         * Even though we're not encrypting the payload, we need
         * to run the cipher to get the auth tag.
         */
        unsigned int nolen = 0;
        status = srtp_cipher_encrypt(session_keys->rtcp_cipher, NULL, &nolen);
        if (status) {
            return srtp_err_status_cipher_fail;
        }
        /*
         * Get the tag and append that to the output
         */
        status = srtp_cipher_get_tag(session_keys->rtcp_cipher, (uint8_t*)auth_tag,
                                     &tag_len);
        if (status) {
            return ( srtp_err_status_cipher_fail);
        }
        enc_octet_len += tag_len;
    }

    /* increase the packet length by the length of the auth tag and seq_num*/
    *pkt_octet_len += (tag_len + sizeof(srtcp_trailer_t));

    /* increase the packet by the mki_size */
    *pkt_octet_len += mki_size;

    return srtp_err_status_ok;
}

/*
 * This function handles incoming SRTCP packets while in AEAD mode,
 * which currently supports AES-GCM encryption.  Note, the auth tag is 
 * at the end of the packet stream and is automatically checked by GCM
 * when decrypting the payload.
 */
static srtp_err_status_t
srtp_unprotect_rtcp_aead (srtp_t ctx, srtp_stream_ctx_t *stream, 
                          void *srtcp_hdr, unsigned int *pkt_octet_len,
                          srtp_session_keys_t *session_keys, unsigned int use_mki)
{
    srtcp_hdr_t *hdr = (srtcp_hdr_t*)srtcp_hdr;
    uint32_t *enc_start;        /* pointer to start of encrypted portion  */
    uint32_t *trailer;          /* pointer to start of trailer            */
    unsigned int enc_octet_len = 0; /* number of octets in encrypted portion */
    uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
    srtp_err_status_t status;
    int tag_len;
    unsigned int tmp_len;
    uint32_t seq_num;
    v128_t iv;
    uint32_t tseq;
    unsigned int mki_size = 0;

    /* get tag length from stream context */
    tag_len = srtp_auth_get_tag_length(session_keys->rtcp_auth);

    if (use_mki) {
      mki_size = session_keys->mki_size;
    }

    /*
     * set encryption start, encryption length, and trailer
     */
    /* index & E (encryption) bit follow normal data.  hdr->len
           is the number of words (32-bit) in the normal packet minus 1 */
    /* This should point trailer to the word past the end of the
           normal data. */
    /* This would need to be modified for optional mikey data */
    /*
     * NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
     *	 multiples of 32-bits (RFC 3550 6.1)
     */
    trailer = (uint32_t*)((char*)hdr + *pkt_octet_len - sizeof(srtcp_trailer_t) - mki_size);
    /*
     * We pass the tag down to the cipher when doing GCM mode 
     */
    enc_octet_len = *pkt_octet_len - (octets_in_rtcp_header + 
                                      sizeof(srtcp_trailer_t) + mki_size);
    auth_tag = (uint8_t*)hdr + *pkt_octet_len - tag_len - mki_size - sizeof(srtcp_trailer_t);

    if (*((unsigned char*)trailer) & SRTCP_E_BYTE_BIT) {
        enc_start = (uint32_t*)hdr + uint32s_in_rtcp_header;
    } else {
        enc_octet_len = 0;
        enc_start = NULL; /* this indicates that there's no encryption */
    }

    /*
     * check the sequence number for replays
     */
    /* this is easier than dealing with bitfield access */
    seq_num = ntohl(*trailer) & SRTCP_INDEX_MASK;
    debug_print(mod_srtp, "srtcp index: %x", seq_num);
    status = srtp_rdb_check(&stream->rtcp_rdb, seq_num);
    if (status) {
        return status;
    }

    /*
     * Calculate and set the IV
     */
    status = srtp_calc_aead_iv_srtcp(session_keys, &iv, seq_num, hdr);
    if (status) {
        return srtp_err_status_cipher_fail;
    }
    status = srtp_cipher_set_iv(session_keys->rtcp_cipher,
                                (uint8_t*)&iv, srtp_direction_decrypt);
    if (status) {
        return srtp_err_status_cipher_fail;
    }

    /*
     * Set the AAD for GCM mode
     */
    if (enc_start) {
        /*
         * If payload encryption is enabled, then the AAD consist of
         * the RTCP header and the seq# at the end of the packet
         */
        status = srtp_cipher_set_aad(session_keys->rtcp_cipher,
                                   (uint8_t*)hdr, octets_in_rtcp_header);
        if (status) {
            return ( srtp_err_status_cipher_fail);
        }
    } else {
        /*
         * Since payload encryption is not enabled, we must authenticate
         * the entire packet as described in RFC 7714 (Section 9.3. Data
         * Types in Unencrypted SRTCP Compound Packets)
         */
        status = srtp_cipher_set_aad(
          session_keys->rtcp_cipher, (uint8_t*)hdr,
          (*pkt_octet_len - tag_len - sizeof(srtcp_trailer_t) - mki_size));
        if (status) {
            return ( srtp_err_status_cipher_fail);
        }
    }

    /*
     * Process the sequence# as AAD
     */
    tseq = *trailer;
    status = srtp_cipher_set_aad(session_keys->rtcp_cipher,
                                 (uint8_t*)&tseq, sizeof(srtcp_trailer_t));
    if (status) {
        return ( srtp_err_status_cipher_fail);
    }

    /* if we're decrypting, exor keystream into the message */
    if (enc_start) {
        status = srtp_cipher_decrypt(session_keys->rtcp_cipher, (uint8_t*)enc_start, &enc_octet_len);
        if (status) {
            return status;
        }
    } else {
        /*
         * Still need to run the cipher to check the tag
         */
        tmp_len = tag_len;
        status = srtp_cipher_decrypt(session_keys->rtcp_cipher, (uint8_t*)auth_tag, &tmp_len);
        if (status) {
            return status;
        }
    }

    /* decrease the packet length by the length of the auth tag and seq_num*/
    *pkt_octet_len -= (tag_len + sizeof(srtcp_trailer_t) + mki_size);

    /*
     * verify that stream is for received traffic - this check will
     * detect SSRC collisions, since a stream that appears in both
     * srtp_protect() and srtp_unprotect() will fail this test in one of
     * those functions.
     *
     * we do this check *after* the authentication check, so that the
     * latter check will catch any attempts to fool us into thinking
     * that we've got a collision
     */
    if (stream->direction != dir_srtp_receiver) {
        if (stream->direction == dir_unknown) {
            stream->direction = dir_srtp_receiver;
        } else {
            srtp_handle_event(ctx, stream, event_ssrc_collision);
        }
    }

    /*
     * if the stream is a 'provisional' one, in which the template context
     * is used, then we need to allocate a new stream at this point, since
     * the authentication passed
     */
    if (stream == ctx->stream_template) {
        srtp_stream_ctx_t *new_stream;

        /*
         * allocate and initialize a new stream
         *
         * note that we indicate failure if we can't allocate the new
         * stream, and some implementations will want to not return
         * failure here
         */
        status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream);
        if (status) {
            return status;
        }

        /* add new stream to the head of the stream_list */
        new_stream->next = ctx->stream_list;
        ctx->stream_list = new_stream;

        /* set stream (the pointer used in this function) */
        stream = new_stream;
    }

    /* we've passed the authentication check, so add seq_num to the rdb */
    srtp_rdb_add_index(&stream->rtcp_rdb, seq_num);

    return srtp_err_status_ok;
}

srtp_err_status_t 
srtp_protect_rtcp(srtp_t ctx, void *rtcp_hdr, int *pkt_octet_len) {
  return srtp_protect_rtcp_mki(ctx, rtcp_hdr, pkt_octet_len, 0, 0);
}

srtp_err_status_t 
srtp_protect_rtcp_mki(srtp_t ctx, void *rtcp_hdr, int *pkt_octet_len,
                      unsigned int use_mki, unsigned int mki_index) {
  srtcp_hdr_t *hdr = (srtcp_hdr_t *)rtcp_hdr;
  uint32_t *enc_start;      /* pointer to start of encrypted portion  */
  uint32_t *auth_start;     /* pointer to start of auth. portion      */
  uint32_t *trailer;        /* pointer to start of trailer            */
  unsigned int enc_octet_len = 0;/* number of octets in encrypted portion */
  uint8_t *auth_tag = NULL; /* location of auth_tag within packet     */
  srtp_err_status_t status;   
  int tag_len;
  srtp_stream_ctx_t *stream;
  uint32_t prefix_len;
  uint32_t seq_num;
  unsigned int mki_size = 0;
  srtp_session_keys_t *session_keys = NULL;

  /* we assume the hdr is 32-bit aligned to start */

  /* check the packet length - it must at least contain a full header */
  if (*pkt_octet_len < octets_in_rtcp_header)
    return srtp_err_status_bad_param;

  /*
   * look up ssrc in srtp_stream list, and process the packet with 
   * the appropriate stream.  if we haven't seen this stream before,
   * there's only one key for this srtp_session, and the cipher
   * supports key-sharing, then we assume that a new stream using
   * that key has just started up
   */
  stream = srtp_get_stream(ctx, hdr->ssrc);
  if (stream == NULL) {
    if (ctx->stream_template != NULL) {
      srtp_stream_ctx_t *new_stream;
      
      /* allocate and initialize a new stream */
      status = srtp_stream_clone(ctx->stream_template,
				 hdr->ssrc, &new_stream); 
      if (status)
	return status;
      
      /* add new stream to the head of the stream_list */
      new_stream->next = ctx->stream_list;
      ctx->stream_list = new_stream;
      
      /* set stream (the pointer used in this function) */
      stream = new_stream;
    } else {
      /* no template stream, so we return an error */
      return srtp_err_status_no_ctx;
    } 
  }
  
  /* 
   * verify that stream is for sending traffic - this check will
   * detect SSRC collisions, since a stream that appears in both
   * srtp_protect() and srtp_unprotect() will fail this test in one of
   * those functions.
   */
  if (stream->direction != dir_srtp_sender) {
    if (stream->direction == dir_unknown) {
      stream->direction = dir_srtp_sender;
    } else {
      srtp_handle_event(ctx, stream, event_ssrc_collision);
    }
  }  

  session_keys = srtp_get_session_keys_with_mki_index(stream, use_mki, mki_index);

  /*
   * Check if this is an AEAD stream (GCM mode).  If so, then dispatch
   * the request to our AEAD handler.
   */
  if (session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_128 ||
      session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_256) {
      return srtp_protect_rtcp_aead(ctx, stream, rtcp_hdr,
                                    (unsigned int*)pkt_octet_len, session_keys,
                                    use_mki);
  }

  /* get tag length from stream context */
  tag_len = srtp_auth_get_tag_length(session_keys->rtcp_auth); 

  /*
   * set encryption start and encryption length - if we're not
   * providing confidentiality, set enc_start to NULL
   */
  enc_start = (uint32_t *)hdr + uint32s_in_rtcp_header;  
  enc_octet_len = *pkt_octet_len - octets_in_rtcp_header;

  /* all of the packet, except the header, gets encrypted */
  /* NOTE: hdr->length is not usable - it refers to only the first
	 RTCP report in the compound packet! */
  /* NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
	 multiples of 32-bits (RFC 3550 6.1) */
  trailer = (uint32_t *) ((char *)enc_start + enc_octet_len);

  if (stream->rtcp_services & sec_serv_conf) {
    *trailer = htonl(SRTCP_E_BIT);     /* set encrypt bit */    
  } else {
    enc_start = NULL;
    enc_octet_len = 0;
	/* 0 is network-order independant */
    *trailer = 0x00000000;     /* set encrypt bit */    
  }

  mki_size = srtp_inject_mki((uint8_t *)hdr + *pkt_octet_len + sizeof(srtcp_trailer_t),
                             session_keys, use_mki);

  /* 
   * set the auth_start and auth_tag pointers to the proper locations
   * (note that srtpc *always* provides authentication, unlike srtp)
   */
  /* Note: This would need to change for optional mikey data */
  auth_start = (uint32_t *)hdr;
  auth_tag = (uint8_t *)hdr + *pkt_octet_len + sizeof(srtcp_trailer_t) + mki_size; 

  /* perform EKT processing if needed */
  srtp_ekt_write_data(stream->ekt, auth_tag, tag_len, pkt_octet_len, 
		      srtp_rdbx_get_packet_index(&stream->rtp_rdbx));

  /* 
   * check sequence number for overruns, and copy it into the packet
   * if its value isn't too big
   */
  status = srtp_rdb_increment(&stream->rtcp_rdb);
  if (status)
    return status;
  seq_num = srtp_rdb_get_value(&stream->rtcp_rdb);
  *trailer |= htonl(seq_num);
  debug_print(mod_srtp, "srtcp index: %x", seq_num);

  /* 
   * if we're using rindael counter mode, set nonce and seq 
   */
  if (session_keys->rtcp_cipher->type->id == SRTP_AES_ICM_128 ||
      session_keys->rtcp_cipher->type->id == SRTP_AES_ICM_192 ||
      session_keys->rtcp_cipher->type->id == SRTP_AES_ICM_256) {
    v128_t iv;
    
    iv.v32[0] = 0;
    iv.v32[1] = hdr->ssrc;  /* still in network order! */
    iv.v32[2] = htonl(seq_num >> 16);
    iv.v32[3] = htonl(seq_num << 16);
    status = srtp_cipher_set_iv(session_keys->rtcp_cipher, (uint8_t*)&iv,
                                srtp_direction_encrypt);

  } else {  
    v128_t iv;
    
    /* otherwise, just set the index to seq_num */  
    iv.v32[0] = 0;
    iv.v32[1] = 0;
    iv.v32[2] = 0;
    iv.v32[3] = htonl(seq_num);
    status = srtp_cipher_set_iv(session_keys->rtcp_cipher,
                                (uint8_t*)&iv, srtp_direction_encrypt);
  }
  if (status)
    return srtp_err_status_cipher_fail;

  /* 
   * if we're authenticating using a universal hash, put the keystream
   * prefix into the authentication tag
   */
  
  /* if auth_start is non-null, then put keystream into tag  */
  if (auth_start) {

    /* put keystream prefix into auth_tag */
    prefix_len = srtp_auth_get_prefix_length(session_keys->rtcp_auth);    
    status = srtp_cipher_output(session_keys->rtcp_cipher, auth_tag, &prefix_len);

    debug_print(mod_srtp, "keystream prefix: %s", 
		srtp_octet_string_hex_string(auth_tag, prefix_len));

    if (status)
      return srtp_err_status_cipher_fail;
  }

  /* if we're encrypting, exor keystream into the message */
  if (enc_start) {
    status = srtp_cipher_encrypt(session_keys->rtcp_cipher, 
		  	        (uint8_t *)enc_start, &enc_octet_len);
    if (status)
      return srtp_err_status_cipher_fail;
  }

  /* initialize auth func context */
  srtp_auth_start(session_keys->rtcp_auth);

  /* 
   * run auth func over packet (including trailer), and write the
   * result at auth_tag 
   */
  status = srtp_auth_compute(session_keys->rtcp_auth,
			(uint8_t *)auth_start, 
			(*pkt_octet_len) + sizeof(srtcp_trailer_t), 
			auth_tag);
  debug_print(mod_srtp, "srtcp auth tag:    %s", 
	      srtp_octet_string_hex_string(auth_tag, tag_len));
  if (status)
    return srtp_err_status_auth_fail;   
    
  /* increase the packet length by the length of the auth tag and seq_num*/
  *pkt_octet_len += (tag_len + sizeof(srtcp_trailer_t));

  /* increase the packet by the mki_size */
  *pkt_octet_len += mki_size;
    
  return srtp_err_status_ok;  
}


srtp_err_status_t 
srtp_unprotect_rtcp(srtp_t ctx, void *srtcp_hdr, int *pkt_octet_len) {
    return srtp_unprotect_rtcp_mki(ctx, srtcp_hdr, pkt_octet_len, 0);
}

srtp_err_status_t
srtp_unprotect_rtcp_mki(srtp_t ctx, void *srtcp_hdr, int *pkt_octet_len,
                        unsigned int use_mki) {
  srtcp_hdr_t *hdr = (srtcp_hdr_t *)srtcp_hdr;
  uint32_t *enc_start;      /* pointer to start of encrypted portion  */
  uint32_t *auth_start;     /* pointer to start of auth. portion      */
  uint32_t *trailer;        /* pointer to start of trailer            */
  unsigned int enc_octet_len = 0;/* number of octets in encrypted portion */
  uint8_t *auth_tag = NULL; /* location of auth_tag within packet     */
  uint8_t tmp_tag[SRTP_MAX_TAG_LEN];
  uint8_t tag_copy[SRTP_MAX_TAG_LEN];
  srtp_err_status_t status;   
  unsigned int auth_len;
  int tag_len;
  srtp_stream_ctx_t *stream;
  uint32_t prefix_len;
  uint32_t seq_num;
  int e_bit_in_packet;     /* whether the E-bit was found in the packet */
  int sec_serv_confidentiality; /* whether confidentiality was requested */
  unsigned int mki_size = 0;
  srtp_session_keys_t *session_keys = NULL;

  /* we assume the hdr is 32-bit aligned to start */

  /* check that the length value is sane; we'll check again once we
     know the tag length, but we at least want to know that it is
     a positive value */
  if (*pkt_octet_len < octets_in_rtcp_header + sizeof(srtcp_trailer_t))
    return srtp_err_status_bad_param;

  /*
   * look up ssrc in srtp_stream list, and process the packet with 
   * the appropriate stream.  if we haven't seen this stream before,
   * there's only one key for this srtp_session, and the cipher
   * supports key-sharing, then we assume that a new stream using
   * that key has just started up
   */
  stream = srtp_get_stream(ctx, hdr->ssrc);
  if (stream == NULL) {
    if (ctx->stream_template != NULL) {
      stream = ctx->stream_template;

      /* 
       * check to see if stream_template has an EKT data structure, in
       * which case we initialize the template using the EKT policy
       * referenced by that data (which consists of decrypting the
       * master key from the EKT field)
       *
       * this function initializes a *provisional* stream, and this
       * stream should not be accepted until and unless the packet
       * passes its authentication check
       */ 
      if (stream->ekt != NULL) {
	status = srtp_stream_init_from_ekt(stream, srtcp_hdr, *pkt_octet_len);
	if (status)
	  return status;
      }

      debug_print(mod_srtp, "srtcp using provisional stream (SSRC: 0x%08x)", 
		  ntohl(hdr->ssrc));
    } else {
      /* no template stream, so we return an error */
      return srtp_err_status_no_ctx;
    } 
  }

  /*
   * Determine if MKI is being used and what session keys should be used
   */
  if (use_mki) {
      session_keys = srtp_get_session_keys(stream, (uint8_t *)hdr,
                                           (const unsigned int*)pkt_octet_len,
                                           &mki_size);

      if (session_keys == NULL) 
         return srtp_err_status_bad_mki;
  } else {
      session_keys = &stream->session_keys[0];
  }  


  /* get tag length from stream context */
  tag_len = srtp_auth_get_tag_length(session_keys->rtcp_auth);

  /* check the packet length - it must contain at least a full RTCP
     header, an auth tag (if applicable), and the SRTCP encrypted flag
     and 31-bit index value */
  if (*pkt_octet_len < (int) (octets_in_rtcp_header + tag_len + mki_size + sizeof(srtcp_trailer_t))) {
    return srtp_err_status_bad_param;
  }

  /*
   * Check if this is an AEAD stream (GCM mode).  If so, then dispatch
   * the request to our AEAD handler.
   */
  if (session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_128 ||
      session_keys->rtp_cipher->algorithm == SRTP_AES_GCM_256) {
      return srtp_unprotect_rtcp_aead(ctx, stream, srtcp_hdr,
                                      (unsigned int*)pkt_octet_len, session_keys,
                                      mki_size);
  }

  sec_serv_confidentiality = stream->rtcp_services == sec_serv_conf ||
      stream->rtcp_services == sec_serv_conf_and_auth;

  /*
   * set encryption start, encryption length, and trailer
   */
  enc_octet_len = *pkt_octet_len - 
                  (octets_in_rtcp_header + tag_len + mki_size + sizeof(srtcp_trailer_t));
  /* index & E (encryption) bit follow normal data.  hdr->len
	 is the number of words (32-bit) in the normal packet minus 1 */
  /* This should point trailer to the word past the end of the
	 normal data. */
  /* This would need to be modified for optional mikey data */
  /*
   * NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
   *	 multiples of 32-bits (RFC 3550 6.1)
   */
  trailer = (uint32_t *) ((char *) hdr +
      *pkt_octet_len -(tag_len + mki_size + sizeof(srtcp_trailer_t)));
  e_bit_in_packet =
      (*((unsigned char *) trailer) & SRTCP_E_BYTE_BIT) == SRTCP_E_BYTE_BIT;
  if (e_bit_in_packet != sec_serv_confidentiality) {
    return srtp_err_status_cant_check;
  }
  if (sec_serv_confidentiality) {
    enc_start = (uint32_t *)hdr + uint32s_in_rtcp_header;  
  } else {
    enc_octet_len = 0;
    enc_start = NULL; /* this indicates that there's no encryption */
  }

  /* 
   * set the auth_start and auth_tag pointers to the proper locations
   * (note that srtcp *always* uses authentication, unlike srtp)
   */
  auth_start = (uint32_t *)hdr;

  /*
   * The location of the auth tag in the packet needs to know MKI 
   * could be present.  The data needed to calculate the Auth tag
   * must not include the MKI
   */
  auth_len = *pkt_octet_len - tag_len - mki_size;
  auth_tag = (uint8_t *)hdr + auth_len + mki_size;

  /* 
   * if EKT is in use, then we make a copy of the tag from the packet,
   * and then zeroize the location of the base tag
   *
   * we first re-position the auth_tag pointer so that it points to
   * the base tag
   */
  if (stream->ekt) {
    auth_tag -= srtp_ekt_octets_after_base_tag(stream->ekt);
    memcpy(tag_copy, auth_tag, tag_len);
    octet_string_set_to_zero(auth_tag, tag_len);
    auth_tag = tag_copy;
    auth_len += tag_len;
  }

  /* 
   * check the sequence number for replays
   */
  /* this is easier than dealing with bitfield access */
  seq_num = ntohl(*trailer) & SRTCP_INDEX_MASK;
  debug_print(mod_srtp, "srtcp index: %x", seq_num);
  status = srtp_rdb_check(&stream->rtcp_rdb, seq_num);
  if (status)
    return status;

  /* 
   * if we're using aes counter mode, set nonce and seq 
   */
  if (session_keys->rtcp_cipher->type->id == SRTP_AES_ICM_128 ||
      session_keys->rtcp_cipher->type->id == SRTP_AES_ICM_192 ||
      session_keys->rtcp_cipher->type->id == SRTP_AES_ICM_256) {
    v128_t iv;

    iv.v32[0] = 0;
    iv.v32[1] = hdr->ssrc; /* still in network order! */
    iv.v32[2] = htonl(seq_num >> 16);
    iv.v32[3] = htonl(seq_num << 16);
    status = srtp_cipher_set_iv(session_keys->rtcp_cipher,
                                (uint8_t*)&iv, srtp_direction_decrypt);

  } else {  
    v128_t iv;
    
    /* otherwise, just set the index to seq_num */  
    iv.v32[0] = 0;
    iv.v32[1] = 0;
    iv.v32[2] = 0;
    iv.v32[3] = htonl(seq_num);
    status = srtp_cipher_set_iv(session_keys->rtcp_cipher,
                                (uint8_t*)&iv, srtp_direction_decrypt);

  }
  if (status)
    return srtp_err_status_cipher_fail;

  /* initialize auth func context */
  srtp_auth_start(session_keys->rtcp_auth);

  /* run auth func over packet, put result into tmp_tag */
  status = srtp_auth_compute(session_keys->rtcp_auth, (uint8_t *)auth_start,
			auth_len, tmp_tag);
  debug_print(mod_srtp, "srtcp computed tag:       %s", 
	      srtp_octet_string_hex_string(tmp_tag, tag_len));
  if (status)
    return srtp_err_status_auth_fail;   
  
  /* compare the tag just computed with the one in the packet */
  debug_print(mod_srtp, "srtcp tag from packet:    %s", 
	      srtp_octet_string_hex_string(auth_tag, tag_len));  
  if (octet_string_is_eq(tmp_tag, auth_tag, tag_len))
    return srtp_err_status_auth_fail;

  /* 
   * if we're authenticating using a universal hash, put the keystream
   * prefix into the authentication tag
   */
  prefix_len = srtp_auth_get_prefix_length(session_keys->rtcp_auth);    
  if (prefix_len) {
    status = srtp_cipher_output(session_keys->rtcp_cipher, auth_tag, &prefix_len);
    debug_print(mod_srtp, "keystream prefix: %s", 
		srtp_octet_string_hex_string(auth_tag, prefix_len));
    if (status)
      return srtp_err_status_cipher_fail;
  }

  /* if we're decrypting, exor keystream into the message */
  if (enc_start) {
    status = srtp_cipher_decrypt(session_keys->rtcp_cipher, (uint8_t *)enc_start,
                                 &enc_octet_len);
    if (status)
      return srtp_err_status_cipher_fail;
  }

  /* decrease the packet length by the length of the auth tag and seq_num */
  *pkt_octet_len -= (tag_len + sizeof(srtcp_trailer_t));

  /* decrease the packet length by the length of the mki_size */
  *pkt_octet_len -= mki_size;

  /*
   * if EKT is in effect, subtract the EKT data out of the packet
   * length
   */
  *pkt_octet_len -= srtp_ekt_octets_after_base_tag(stream->ekt);

  /* 
   * verify that stream is for received traffic - this check will
   * detect SSRC collisions, since a stream that appears in both
   * srtp_protect() and srtp_unprotect() will fail this test in one of
   * those functions.
   *
   * we do this check *after* the authentication check, so that the
   * latter check will catch any attempts to fool us into thinking
   * that we've got a collision
   */
  if (stream->direction != dir_srtp_receiver) {
    if (stream->direction == dir_unknown) {
      stream->direction = dir_srtp_receiver;
    } else {
      srtp_handle_event(ctx, stream, event_ssrc_collision);
    }
  }

  /* 
   * if the stream is a 'provisional' one, in which the template context
   * is used, then we need to allocate a new stream at this point, since
   * the authentication passed
   */
  if (stream == ctx->stream_template) {  
    srtp_stream_ctx_t *new_stream;

    /* 
     * allocate and initialize a new stream 
     * 
     * note that we indicate failure if we can't allocate the new
     * stream, and some implementations will want to not return
     * failure here
     */
    status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream); 
    if (status)
      return status;
    
    /* add new stream to the head of the stream_list */
    new_stream->next = ctx->stream_list;
    ctx->stream_list = new_stream;
    
    /* set stream (the pointer used in this function) */
    stream = new_stream;
  }

  /* we've passed the authentication check, so add seq_num to the rdb */
  srtp_rdb_add_index(&stream->rtcp_rdb, seq_num);
    
    
  return srtp_err_status_ok;  
}


/*
 * user data within srtp_t context
 */

void
srtp_set_user_data(srtp_t ctx, void *data) {
  ctx->user_data = data;
}

void*
srtp_get_user_data(srtp_t ctx) {
  return ctx->user_data;
}


/*
 * dtls keying for srtp 
 */

srtp_err_status_t
srtp_crypto_policy_set_from_profile_for_rtp(srtp_crypto_policy_t *policy, 
				            srtp_profile_t profile) {

  /* set SRTP policy from the SRTP profile in the key set */
  switch(profile) {
  case srtp_profile_aes128_cm_sha1_80:
    srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
    break;
  case srtp_profile_aes128_cm_sha1_32:
    srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(policy);
    break;
  case srtp_profile_null_sha1_80:
    srtp_crypto_policy_set_null_cipher_hmac_sha1_80(policy);
    break;
#if defined(OPENSSL)
  case srtp_profile_aead_aes_128_gcm:
    srtp_crypto_policy_set_aes_gcm_128_16_auth(policy);
    break;
  case srtp_profile_aead_aes_256_gcm:
    srtp_crypto_policy_set_aes_gcm_256_16_auth(policy);
    break;
#endif
    /* the following profiles are not (yet) supported */
  case srtp_profile_null_sha1_32:
  default:
    return srtp_err_status_bad_param;
  }

  return srtp_err_status_ok;
}

srtp_err_status_t
srtp_crypto_policy_set_from_profile_for_rtcp(srtp_crypto_policy_t *policy, 
					     srtp_profile_t profile) {

  /* set SRTP policy from the SRTP profile in the key set */
  switch(profile) {
  case srtp_profile_aes128_cm_sha1_80:
    srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
    break;
  case srtp_profile_aes128_cm_sha1_32:
    /* We do not honor the 32-bit auth tag request since
     * this is not compliant with RFC 3711 */
    srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
    break;
  case srtp_profile_null_sha1_80:
    srtp_crypto_policy_set_null_cipher_hmac_sha1_80(policy);
    break;
#if defined(OPENSSL)
  case srtp_profile_aead_aes_128_gcm:
    srtp_crypto_policy_set_aes_gcm_128_16_auth(policy);
    break;
  case srtp_profile_aead_aes_256_gcm:
    srtp_crypto_policy_set_aes_gcm_256_16_auth(policy);
    break;
#endif
    /* the following profiles are not (yet) supported */
  case srtp_profile_null_sha1_32:
  default:
    return srtp_err_status_bad_param;
  }

  return srtp_err_status_ok;
}

void srtp_append_salt_to_key(uint8_t *key, unsigned int bytes_in_key, uint8_t *salt, unsigned int bytes_in_salt) {
  memcpy(key + bytes_in_key, salt, bytes_in_salt);
}

unsigned int
srtp_profile_get_master_key_length(srtp_profile_t profile) {

  switch(profile) {
  case srtp_profile_aes128_cm_sha1_80:
    return SRTP_AES_128_KEY_LEN;
    break;
  case srtp_profile_aes128_cm_sha1_32:
    return SRTP_AES_128_KEY_LEN;
    break;
  case srtp_profile_null_sha1_80:
    return SRTP_AES_128_KEY_LEN;
    break;
  case srtp_profile_aead_aes_128_gcm:
    return SRTP_AES_128_KEY_LEN;
    break;
  case srtp_profile_aead_aes_256_gcm:
    return SRTP_AES_256_KEY_LEN;
    break;
    /* the following profiles are not (yet) supported */
  case srtp_profile_null_sha1_32:
  default:
    return 0;  /* indicate error by returning a zero */
  }
}

unsigned int
srtp_profile_get_master_salt_length(srtp_profile_t profile) {

  switch(profile) {
  case srtp_profile_aes128_cm_sha1_80:
    return SRTP_SALT_LEN;
    break;
  case srtp_profile_aes128_cm_sha1_32:
    return SRTP_SALT_LEN;
    break;
  case srtp_profile_null_sha1_80:
    return SRTP_SALT_LEN;
    break;
  case srtp_profile_aead_aes_128_gcm:
    return SRTP_AEAD_SALT_LEN;
    break;
  case srtp_profile_aead_aes_256_gcm:
    return SRTP_AEAD_SALT_LEN;
    break;
    /* the following profiles are not (yet) supported */
  case srtp_profile_null_sha1_32:
  default:
    return 0;  /* indicate error by returning a zero */
  }
}

srtp_err_status_t
srtp_get_protect_trailer_length(srtp_t session,
                                uint32_t use_mki,
                                uint32_t mki_index,
                                uint32_t *length) 
{
    srtp_stream_ctx_t *stream;

    if (session == NULL)
      return srtp_err_status_bad_param;

    *length = 0;

    /* Try obtaining stream from stream_list */
    stream = session->stream_list;

    if (stream == NULL) {
        /* Try obtaining the template stream */
        stream = session->stream_template;
    }

    if (stream == NULL) {
        return srtp_err_status_bad_param;
    }

    if (use_mki) {
       if (mki_index > stream->num_master_keys)
           return srtp_err_status_bad_mki;

       *length += stream->session_keys[mki_index].mki_size;
       *length += srtp_auth_get_tag_length(stream->session_keys[mki_index].rtp_auth);
    } else {
       *length += srtp_auth_get_tag_length(stream->session_keys[0].rtp_auth);
    }

    return srtp_err_status_ok;
}

srtp_err_status_t
srtp_get_protect_rtcp_trailer_length(srtp_t session,
                                     uint32_t use_mki,
                                     uint32_t mki_index,
                                     uint32_t *length) 
{
    srtp_stream_ctx_t *stream;

    if (session == NULL)
      return srtp_err_status_bad_param;

    *length = 0;

    /* Try obtaining stream from stream_list */
    stream = session->stream_list;

    if (stream == NULL) {
        /* Try obtaining the template stream */
        stream = session->stream_template;
    }

    if (stream == NULL) {
        return srtp_err_status_bad_param;
    }

    if (use_mki) {
       if (mki_index > stream->num_master_keys)
           return srtp_err_status_bad_mki;

       *length += stream->session_keys[mki_index].mki_size;
       *length += srtp_auth_get_tag_length(stream->session_keys[mki_index].rtcp_auth);
    } else {
       *length += srtp_auth_get_tag_length(stream->session_keys[0].rtcp_auth);
    }
 
    *length += sizeof(srtcp_trailer_t);

    return srtp_err_status_ok;
}


/*
 * SRTP debug interface
 */
srtp_err_status_t srtp_set_debug_module(const char *mod_name, int v)
{
    return srtp_crypto_kernel_set_debug_module(mod_name, v);
}

srtp_err_status_t srtp_list_debug_modules(void)
{
    return srtp_crypto_kernel_list_debug_modules();
}

/*
 * srtp_log_handler is a global variable holding a pointer to the
 * log handler function; this function is called for any log
 * output.
 */

static srtp_log_handler_func_t *srtp_log_handler = NULL;
static void * srtp_log_handler_data = NULL;

void srtp_err_handler(srtp_err_reporting_level_t level, const char * msg)
{
    if (srtp_log_handler) {
        srtp_log_level_t log_level = srtp_log_level_error;
        switch(level) {
            case srtp_err_level_error: log_level = srtp_log_level_error; break;
            case srtp_err_level_warning: log_level = srtp_log_level_warning; break;
            case srtp_err_level_info: log_level = srtp_log_level_info; break;
            case srtp_err_level_debug: log_level = srtp_log_level_debug; break;
        }

        srtp_log_handler(log_level, msg, srtp_log_handler_data);
    }
}

srtp_err_status_t srtp_install_log_handler(srtp_log_handler_func_t func, void * data)
{

    /*
     * note that we accept NULL arguments intentionally - calling this
     * function with a NULL arguments removes a log handler that's
     * been previously installed
     */

    if (srtp_log_handler) {
        srtp_install_err_report_handler(NULL);
    }
    srtp_log_handler = func;
    srtp_log_handler_data = data;
    if (srtp_log_handler) {
        srtp_install_err_report_handler(srtp_err_handler);
    }
    return srtp_err_status_ok;
}