summaryrefslogtreecommitdiff
path: root/agent/conncheck.c
blob: 41d8c92c599c38df48e4461bd09888f73c30bdda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
/*
 * This file is part of the Nice GLib ICE library.
 *
 * (C) 2006-2009 Collabora Ltd.
 *  Contact: Youness Alaoui
 * (C) 2006-2009 Nokia Corporation. All rights reserved.
 *  Contact: Kai Vehmanen
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Nice GLib ICE library.
 *
 * The Initial Developers of the Original Code are Collabora Ltd and Nokia
 * Corporation. All Rights Reserved.
 *
 * Contributors:
 *   Kai Vehmanen, Nokia
 *   Youness Alaoui, Collabora Ltd.
 *   Dafydd Harries, Collabora Ltd.
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

/*
 * @file conncheck.c
 * @brief ICE connectivity checks
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <errno.h>
#include <string.h>

#include <glib.h>

#include "debug.h"

#include "agent.h"
#include "agent-priv.h"
#include "conncheck.h"
#include "discovery.h"
#include "stun/stun5389.h"
#include "stun/usages/ice.h"
#include "stun/usages/bind.h"
#include "stun/usages/turn.h"

static void priv_update_check_list_failed_components (NiceAgent *agent, NiceStream *stream);
static guint priv_prune_pending_checks (NiceAgent *agent, NiceStream *stream, NiceComponent *component);
static gboolean priv_schedule_triggered_check (NiceAgent *agent, NiceStream *stream, NiceComponent *component, NiceSocket *local_socket, NiceCandidate *remote_cand);
static void priv_mark_pair_nominated (NiceAgent *agent, NiceStream *stream, NiceComponent *component, NiceCandidate *localcand, NiceCandidate *remotecand);
static size_t priv_create_username (NiceAgent *agent, NiceStream *stream,
    guint component_id, NiceCandidate *remote, NiceCandidate *local,
    uint8_t *dest, guint dest_len, gboolean inbound);
static size_t priv_get_password (NiceAgent *agent, NiceStream *stream,
    NiceCandidate *remote, uint8_t **password);
static void candidate_check_pair_free (NiceAgent *agent,
    CandidateCheckPair *pair);
static CandidateCheckPair *priv_conn_check_add_for_candidate_pair_matched (
    NiceAgent *agent, guint stream_id, NiceComponent *component,
    NiceCandidate *local, NiceCandidate *remote, NiceCheckState initial_state);
static gboolean priv_conn_keepalive_tick_agent_locked (NiceAgent *agent,
    gpointer pointer);

static gint64 priv_timer_remainder (gint64 timer, gint64 now)
{
  if (now >= timer)
    return 0;

  return (timer - now) / 1000;
}

static gchar
priv_state_to_gchar (NiceCheckState state)
{
  switch (state) {
    case NICE_CHECK_WAITING:
      return 'W';
    case NICE_CHECK_IN_PROGRESS:
      return 'I';
    case NICE_CHECK_SUCCEEDED:
      return 'S';
    case NICE_CHECK_FAILED:
      return 'F';
    case NICE_CHECK_FROZEN:
      return 'Z';
    case NICE_CHECK_DISCOVERED:
      return 'D';
    default:
      g_assert_not_reached ();
  }
}

static const gchar *
priv_state_to_string (NiceCheckState state)
{
  switch (state) {
    case NICE_CHECK_WAITING:
      return "WAITING";
    case NICE_CHECK_IN_PROGRESS:
      return "IN_PROGRESS";
    case NICE_CHECK_SUCCEEDED:
      return "SUCCEEDED";
    case NICE_CHECK_FAILED:
      return "FAILED";
    case NICE_CHECK_FROZEN:
      return "FROZEN";
    case NICE_CHECK_DISCOVERED:
      return "DISCOVERED";
    default:
      g_assert_not_reached ();
  }
}

#define SET_PAIR_STATE( a, p, s ) G_STMT_START{\
  g_assert (p); \
  p->state = s; \
  nice_debug ("Agent %p : pair %p state %s (%s)", \
      a, p, priv_state_to_string (s), G_STRFUNC); \
}G_STMT_END

static const gchar *
priv_ice_return_to_string (StunUsageIceReturn ice_return)
{
  switch (ice_return) {
    case STUN_USAGE_ICE_RETURN_SUCCESS:
      return "success";
    case STUN_USAGE_ICE_RETURN_ERROR:
      return "error";
    case STUN_USAGE_ICE_RETURN_INVALID:
      return "invalid";
    case STUN_USAGE_ICE_RETURN_ROLE_CONFLICT:
      return "role conflict";
    case STUN_USAGE_ICE_RETURN_INVALID_REQUEST:
      return "invalid request";
    case STUN_USAGE_ICE_RETURN_INVALID_METHOD:
      return "invalid method";
    case STUN_USAGE_ICE_RETURN_MEMORY_ERROR:
      return "memory error";
    case STUN_USAGE_ICE_RETURN_INVALID_ADDRESS:
      return "invalid address";
    case STUN_USAGE_ICE_RETURN_NO_MAPPED_ADDRESS:
      return "no mapped address";
    default:
      g_assert_not_reached ();
  }
}

static const gchar *
priv_candidate_type_to_string (NiceCandidateType type)
{
  switch (type) {
    case NICE_CANDIDATE_TYPE_HOST:
      return "host";
    case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
      return "srflx";
    case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
      return "prflx";
    case NICE_CANDIDATE_TYPE_RELAYED:
      return "relay";
    default:
      g_assert_not_reached ();
  }
}

static const gchar *
priv_candidate_transport_to_string (NiceCandidateTransport transport)
{
  switch (transport) {
    case NICE_CANDIDATE_TRANSPORT_UDP:
      return "udp";
    case NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE:
      return "tcp-act";
    case NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE:
      return "tcp-pass";
    case NICE_CANDIDATE_TRANSPORT_TCP_SO:
      return "tcp-so";
    default:
      g_assert_not_reached ();
  }
}

static const gchar *
priv_socket_type_to_string (NiceSocketType type)
{
  switch (type) {
    case NICE_SOCKET_TYPE_UDP_BSD:
      return "udp";
    case NICE_SOCKET_TYPE_TCP_BSD:
      return "tcp";
    case NICE_SOCKET_TYPE_PSEUDOSSL:
      return "ssl";
    case NICE_SOCKET_TYPE_HTTP:
      return "http";
    case NICE_SOCKET_TYPE_SOCKS5:
      return "socks";
    case NICE_SOCKET_TYPE_UDP_TURN:
      return "udp-turn";
    case NICE_SOCKET_TYPE_UDP_TURN_OVER_TCP:
      return "tcp-turn";
    case NICE_SOCKET_TYPE_TCP_ACTIVE:
      return "tcp-act";
    case NICE_SOCKET_TYPE_TCP_PASSIVE:
      return "tcp-pass";
    case NICE_SOCKET_TYPE_TCP_SO:
      return "tcp-so";
    default:
      g_assert_not_reached ();
  }
}

/*
 * Dump the component list of incoming checks
 */
static void
print_component_incoming_checks (NiceAgent *agent, NiceStream *stream,
  NiceComponent *component)
{
  GList *i;

  for (i = component->incoming_checks.head; i; i = i->next) {
    IncomingCheck *icheck = i->data;
    gchar tmpbuf1[INET6_ADDRSTRLEN] = {0};
    gchar tmpbuf2[INET6_ADDRSTRLEN] = {0};

    nice_address_to_string (&icheck->local_socket->addr, tmpbuf1);
    nice_address_to_string (&icheck->from, tmpbuf2);
    nice_debug ("Agent %p : *** sc=%d/%d : icheck %p : "
      "sock %s [%s]:%u > [%s]:%u",
      agent, stream->id, component->id, icheck,
      priv_socket_type_to_string (icheck->local_socket->type),
      tmpbuf1, nice_address_get_port (&icheck->local_socket->addr),
      tmpbuf2, nice_address_get_port (&icheck->from));
  }
}

/*
 * Dump the conncheck lists of the agent
 */
static void
priv_print_conn_check_lists (NiceAgent *agent, const gchar *where, const gchar *detail)
{
  GSList *i, *k, *l;
  guint j, m;
  gint64 now;

  if (!nice_debug_is_verbose ())
    return;

  now = g_get_monotonic_time ();

#define PRIORITY_LEN 32

  nice_debug ("Agent %p : *** conncheck list DUMP (called from %s%s)",
      agent, where, detail ? detail : "");
  nice_debug ("Agent %p : *** agent nomination mode %s, %s",
      agent, agent->nomination_mode == NICE_NOMINATION_MODE_AGGRESSIVE ?
      "aggressive" : "regular",
      agent->controlling_mode ? "controlling" : "controlled");
  for (i = agent->streams; i ; i = i->next) {
    NiceStream *stream = i->data;
    for (j = 1; j <= stream->n_components; j++) {
      NiceComponent *component;
      for (k = stream->conncheck_list; k ; k = k->next) {
        CandidateCheckPair *pair = k->data;
        if (pair->component_id == j) {
          gchar local_addr[INET6_ADDRSTRLEN];
          gchar remote_addr[INET6_ADDRSTRLEN];
          gchar priority[NICE_CANDIDATE_PAIR_PRIORITY_MAX_SIZE];

          nice_address_to_string (&pair->local->addr, local_addr);
          nice_address_to_string (&pair->remote->addr, remote_addr);
          nice_candidate_pair_priority_to_string (pair->priority, priority);

          nice_debug ("Agent %p : *** sc=%d/%d : pair %p : "
              "f=%s t=%s:%s sock=%s "
              "%s:[%s]:%u > %s:[%s]:%u prio=%s/%08x state=%c%s%s%s%s",
              agent, pair->stream_id, pair->component_id, pair,
              pair->foundation,
              priv_candidate_type_to_string (pair->local->type),
              priv_candidate_type_to_string (pair->remote->type),
              priv_socket_type_to_string (pair->sockptr->type),
              priv_candidate_transport_to_string (pair->local->transport),
              local_addr, nice_address_get_port (&pair->local->addr),
              priv_candidate_transport_to_string (pair->remote->transport),
              remote_addr, nice_address_get_port (&pair->remote->addr),
              priority, pair->stun_priority,
              priv_state_to_gchar (pair->state),
              pair->valid ? "V" : "",
              pair->nominated ? "N" : "",
              pair->use_candidate_on_next_check ? "C" : "",
              g_slist_find (agent->triggered_check_queue, pair) ? "T" : "");

          for (l = pair->stun_transactions, m = 0; l; l = l->next, m++) {
            StunTransaction *stun = l->data;
            nice_debug ("Agent %p : *** sc=%d/%d : pair %p :   "
                "stun#=%d timer=%d/%d %" G_GINT64_FORMAT "/%dms buf=%p %s",
                agent, pair->stream_id, pair->component_id, pair, m,
                stun->timer.retransmissions, stun->timer.max_retransmissions,
                stun->timer.delay - priv_timer_remainder (stun->next_tick, now),
                stun->timer.delay,
                stun->message.buffer,
                (m == 0 && pair->retransmit) ? "(R)" : "");
          }
        }
      }
      if (agent_find_component (agent, stream->id, j, NULL, &component))
        print_component_incoming_checks (agent, stream, component);
    }
  }
}

/* Add the pair to the triggered checks list, if not already present
 */
static void
priv_add_pair_to_triggered_check_queue (NiceAgent *agent, CandidateCheckPair *pair)
{
  g_assert (pair);

  SET_PAIR_STATE (agent, pair, NICE_CHECK_IN_PROGRESS);
  if (agent->triggered_check_queue == NULL ||
      g_slist_find (agent->triggered_check_queue, pair) == NULL)
    agent->triggered_check_queue = g_slist_append (agent->triggered_check_queue, pair);
}

/* Remove the pair from the triggered checks list
 */
static void
priv_remove_pair_from_triggered_check_queue (NiceAgent *agent, CandidateCheckPair *pair)
{
  g_assert (pair);
  agent->triggered_check_queue = g_slist_remove (agent->triggered_check_queue, pair);
}

/* Get the pair from the triggered checks list
 */
static CandidateCheckPair *
priv_get_pair_from_triggered_check_queue (NiceAgent *agent)
{
  CandidateCheckPair *pair = NULL;

  if (agent->triggered_check_queue) {
    pair = (CandidateCheckPair *)agent->triggered_check_queue->data;
    priv_remove_pair_from_triggered_check_queue (agent, pair);
  }
  return pair;
}

/*
 * Check if the conncheck list if Active according to
 * ICE spec, 5.7.4 (Computing States)
 *
 * note: the ICE spec in unclear about that, but the check list should
 * be considered active when there is at least a pair in Waiting state
 * OR a pair in In-Progress state.
 */
static gboolean
priv_is_checklist_active (NiceStream *stream)
{
  GSList *i;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_WAITING || p->state == NICE_CHECK_IN_PROGRESS)
      return TRUE;
  }
  return FALSE;
}

/*
 * Check if the conncheck list if Frozen according to
 * ICE spec, 5.7.4 (Computing States)
 */
static gboolean
priv_is_checklist_frozen (NiceStream *stream)
{
  GSList *i;

  if (stream->conncheck_list == NULL)
    return FALSE;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state != NICE_CHECK_FROZEN)
      return FALSE;
  }
  return TRUE;
}

/*
 * Check if all components of the stream have
 * a valid pair (used for ICE spec, 7.1.3.2.3, point 2.)
 */
static gboolean
priv_all_components_have_valid_pair (NiceStream *stream)
{
  guint i;
  GSList *j;

  for (i = 1; i <= stream->n_components; i++) {
    for (j = stream->conncheck_list; j ; j = j->next) {
      CandidateCheckPair *p = j->data;
      if (p->component_id == i && p->valid)
        break;
    }
    if (j == NULL)
      return FALSE;
  }
  return TRUE;
}

/*
 * Check if the foundation in parameter matches the foundation
 * of a valid pair in the conncheck list [of stream] (used for ICE spec,
 * 7.1.3.2.3, point 2.)
 */
static gboolean
priv_foundation_matches_a_valid_pair (const gchar *foundation, NiceStream *stream)
{
  GSList *i;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->valid &&
        strncmp (p->foundation, foundation,
            NICE_CANDIDATE_PAIR_MAX_FOUNDATION) == 0)
      return TRUE;
  }
  return FALSE;
}

/*
 * Finds the next connectivity check in WAITING state.
 */
static CandidateCheckPair *priv_conn_check_find_next_waiting (GSList *conn_check_list)
{
  GSList *i;

  /* note: list is sorted in priority order to first waiting check has
   *       the highest priority */
  for (i = conn_check_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_WAITING)
      return p;
  }

  return NULL;
}

/*
 * Finds the next connectivity check in FROZEN state.
 */
static CandidateCheckPair *
priv_conn_check_find_next_frozen (GSList *conn_check_list)
{
  GSList *i;

  /* note: list is sorted in priority order to first frozen check has
   *       the highest priority */
  for (i = conn_check_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_FROZEN)
      return p;
  }

  return NULL;
}

/*
 * Returns the number of active check lists of the agent
 */
static guint
priv_number_of_active_check_lists (NiceAgent *agent)
{
  guint n = 0;
  GSList *i;

  for (i = agent->streams; i ; i = i->next)
    if (priv_is_checklist_active (i->data))
      n++;
  return n;
}

/*
 * Returns the first stream of the agent having a Frozen
 * connection check list
 */
static NiceStream *
priv_find_first_frozen_check_list (NiceAgent *agent)
{
  GSList *i;

  for (i = agent->streams; i ; i = i->next) {
    NiceStream *stream = i->data;
    if (priv_is_checklist_frozen (stream))
      return stream;
  }
  return NULL;
}

/*
 * Initiates a new connectivity check for a ICE candidate pair.
 *
 * @return TRUE on success, FALSE on error
 */
static gboolean priv_conn_check_initiate (NiceAgent *agent, CandidateCheckPair *pair)
{
  SET_PAIR_STATE (agent, pair, NICE_CHECK_IN_PROGRESS);
  if (conn_check_send (agent, pair)) {
    SET_PAIR_STATE (agent, pair, NICE_CHECK_FAILED);
    return FALSE;
  }
  return TRUE;
}

/*
 * Unfreezes the next connectivity check in the list. Follows the
 * algorithm (2.) defined in 5.7.4 (Computing States) of the ICE spec
 * (RFC5245)
 *
 * See also sect 7.1.2.2.3 (Updating Pair States), and
 * priv_conn_check_unfreeze_related().
 * 
 * @return TRUE on success, and FALSE if no frozen candidates were found.
 */
static gboolean priv_conn_check_unfreeze_next (NiceAgent *agent, NiceStream *stream)
{
  GSList *i, *j;
  GSList *found_list = NULL;
  gboolean result = FALSE;

  priv_print_conn_check_lists (agent, G_STRFUNC, NULL);

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p1 = i->data;
    CandidateCheckPair *pair = NULL;
    guint lowest_component_id = stream->n_components + 1;
    guint64 highest_priority = 0;

    if (g_slist_find_custom (found_list, p1->foundation, (GCompareFunc)strcmp))
      continue;
    found_list = g_slist_prepend (found_list, p1->foundation);

    for (j = stream->conncheck_list; j ; j = j->next) {
      CandidateCheckPair *p2 = i->data;
      if (strncmp (p2->foundation, p1->foundation,
              NICE_CANDIDATE_PAIR_MAX_FOUNDATION) == 0) {
        if (p2->component_id < lowest_component_id ||
            (p2->component_id == lowest_component_id &&
             p2->priority > highest_priority)) {
          pair = p2;
          lowest_component_id = p2->component_id;
          highest_priority = p2->priority;
        }
      }
    }

    if (pair) {
      nice_debug ("Agent %p : Pair %p with s/c-id %u/%u (%s) unfrozen.",
          agent, pair, pair->stream_id, pair->component_id, pair->foundation);
      SET_PAIR_STATE (agent, pair, NICE_CHECK_WAITING);
      result = TRUE;
    }
  }
  g_slist_free (found_list);
  return result;
}

/*
 * Unfreezes the next next connectivity check in the list after
 * check 'success_check' has successfully completed.
 *
 * See sect 7.1.2.2.3 (Updating Pair States) of ICE spec (ID-19).
 * 
 * @param agent context
 * @param ok_check a connectivity check that has just completed
 *
 * @return TRUE on success, and FALSE if no frozen candidates were found.
 */
static void priv_conn_check_unfreeze_related (NiceAgent *agent, NiceStream *stream, CandidateCheckPair *ok_check)
{
  GSList *i, *j;

  g_assert (ok_check);
  g_assert_cmpint (ok_check->state, ==, NICE_CHECK_SUCCEEDED);
  g_assert (stream);
  g_assert_cmpuint (stream->id, ==, ok_check->stream_id);

  priv_print_conn_check_lists (agent, G_STRFUNC, NULL);

  /* step: perform the step (1) of 'Updating Pair States' */
  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
   
    if (p->stream_id == ok_check->stream_id) {
      if (p->state == NICE_CHECK_FROZEN &&
          strncmp (p->foundation, ok_check->foundation,
              NICE_CANDIDATE_PAIR_MAX_FOUNDATION) == 0) {
	nice_debug ("Agent %p : Unfreezing check %p (after successful check %p).", agent, p, ok_check);
	SET_PAIR_STATE (agent, p, NICE_CHECK_WAITING);
      }
    }
  }

  /* step: perform the step (2) of 'Updating Pair States' */
  stream = agent_find_stream (agent, ok_check->stream_id);
  if (priv_all_components_have_valid_pair (stream)) {
    for (i = agent->streams; i ; i = i->next) {
      /* the agent examines the check list for each other
       * media stream in turn
       */
      NiceStream *s = i->data;
      if (s->id == ok_check->stream_id)
        continue;
      if (priv_is_checklist_active (s)) {
        /* checklist is Active
         */
        for (j = s->conncheck_list; j ; j = j->next) {
	  CandidateCheckPair *p = j->data;
          if (p->state == NICE_CHECK_FROZEN &&
              priv_foundation_matches_a_valid_pair (p->foundation, stream)) {
	    nice_debug ("Agent %p : Unfreezing check %p from stream %u (after successful check %p).", agent, p, s->id, ok_check);
	    SET_PAIR_STATE (agent, p, NICE_CHECK_WAITING);
          }
        }
      } else if (priv_is_checklist_frozen (s)) {
        /* checklist is Frozen
         */
        gboolean match_found = FALSE;
        /* check if there is one pair in the check list whose
         * foundation matches a pair in the valid list under
         * consideration
         */
        for (j = s->conncheck_list; j ; j = j->next) {
	  CandidateCheckPair *p = j->data;
          if (priv_foundation_matches_a_valid_pair (p->foundation, stream)) {
            match_found = TRUE;
            nice_debug ("Agent %p : Unfreezing check %p from stream %u (after successful check %p).", agent, p, s->id, ok_check);
            SET_PAIR_STATE (agent, p, NICE_CHECK_WAITING);
          }
        }

        if (!match_found) {
          /* set the pair with the lowest component ID
           * and highest priority to Waiting
           */
          priv_conn_check_unfreeze_next (agent, s);
        }
      }
    }
  }    
}

/*
 * Create a new STUN transaction and add it to the list
 * of ongoing stun transactions of a pair.
 *
 * @pair the pair the new stun transaction should be added to.
 * @return the created stun transaction.
 */
static StunTransaction *
priv_add_stun_transaction (CandidateCheckPair *pair)
{
  StunTransaction *stun = g_slice_new0 (StunTransaction);
  pair->stun_transactions = g_slist_prepend (pair->stun_transactions, stun);
  pair->retransmit = TRUE;
  return stun;
}

/*
 * Forget a STUN transaction.
 *
 * @data the stun transaction to be forgotten.
 * @user_data the component contained the concerned stun agent.
 */
static void
priv_forget_stun_transaction (gpointer data, gpointer user_data)
{
  StunTransaction *stun = data;
  NiceComponent *component = user_data;
  StunTransactionId id;

  if (stun->message.buffer != NULL) {
    stun_message_id (&stun->message, id);
    stun_agent_forget_transaction (&component->stun_agent, id);
  }
}

static void
priv_free_stun_transaction (gpointer data)
{
  g_slice_free (StunTransaction, data);
}

/*
 * Remove a STUN transaction from a pair, and forget it
 * from the related component stun agent.
 *
 * @pair the pair the stun transaction should be removed from.
 * @stun the stun transaction to be removed.
 * @component the component containing the stun agent used to
 * forget the stun transaction.
 */
static void
priv_remove_stun_transaction (CandidateCheckPair *pair,
  StunTransaction *stun, NiceComponent *component)
{
  priv_forget_stun_transaction (stun, component);
  pair->stun_transactions = g_slist_remove (pair->stun_transactions, stun);
  priv_free_stun_transaction (stun);
}

/*
 * Remove all STUN transactions from a pair, and forget them
 * from the related component stun agent.
 *
 * @pair the pair the stun list should be cleared.
 * @component the component containing the stun agent used to
 * forget the stun transactions.
 */
static void
priv_free_all_stun_transactions (CandidateCheckPair *pair,
  NiceComponent *component)
{
  if (component)
    g_slist_foreach (pair->stun_transactions, priv_forget_stun_transaction, component);
  g_slist_free_full (pair->stun_transactions, priv_free_stun_transaction);
  pair->stun_transactions = NULL;
}

static void
candidate_check_pair_fail (NiceStream *stream, NiceAgent *agent, CandidateCheckPair *p)
{
  NiceComponent *component;

  component = nice_stream_find_component_by_id (stream, p->component_id);
  SET_PAIR_STATE (agent, p, NICE_CHECK_FAILED);
  priv_free_all_stun_transactions (p, component);
}

/*
 * Helper function for connectivity check timer callback that
 * runs through the stream specific part of the state machine. 
 *
 * @param schedule if TRUE, schedule a new check
 *
 * @return will return FALSE when no more pending timers.
 */
static gboolean priv_conn_check_tick_stream (NiceStream *stream, NiceAgent *agent)
{
  gboolean keep_timer_going = FALSE;
  GSList *i, *j;
  CandidateCheckPair *pair;
  unsigned int timeout;
  gint64 now;

  now = g_get_monotonic_time ();

  /* step: process ongoing STUN transactions */
  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    gchar tmpbuf1[INET6_ADDRSTRLEN], tmpbuf2[INET6_ADDRSTRLEN];
    NiceComponent *component;
    guint index = 0, remaining = 0;

    if (p->stun_transactions == NULL)
      continue;

    if (p->state != NICE_CHECK_IN_PROGRESS)
      continue;

    if (!agent_find_component (agent, p->stream_id, p->component_id,
        NULL, &component))
      continue;

    j = p->stun_transactions;
    while (j) {
      StunTransaction *stun = j->data;
      GSList *next = j->next;

      if (now < stun->next_tick)
        remaining++;
      else
        switch (stun_timer_refresh (&stun->timer)) {
          case STUN_USAGE_TIMER_RETURN_TIMEOUT:
timer_return_timeout:
            priv_remove_stun_transaction (p, stun, component);
            break;
          case STUN_USAGE_TIMER_RETURN_RETRANSMIT:
            /* case: retransmission stopped, due to the nomination of
             * a pair with a higher priority than this in-progress pair,
             * ICE spec, sect 8.1.2 "Updating States", item 2.2
             */
            if (!p->retransmit || index > 0)
              goto timer_return_timeout;

            /* case: not ready, so schedule a new timeout */
            timeout = stun_timer_remainder (&stun->timer);

            nice_debug ("Agent %p :STUN transaction retransmitted on pair %p "
                "(timer=%d/%d %d/%dms).",
                agent, p,
                stun->timer.retransmissions, stun->timer.max_retransmissions,
                stun->timer.delay - timeout, stun->timer.delay);

            agent_socket_send (p->sockptr, &p->remote->addr,
                stun_message_length (&stun->message),
                (gchar *)stun->buffer);

            /* note: convert from milli to microseconds for g_time_val_add() */
            stun->next_tick = now + timeout * 1000;

            return TRUE;
          case STUN_USAGE_TIMER_RETURN_SUCCESS:
            timeout = stun_timer_remainder (&stun->timer);
            /* note: convert from milli to microseconds for g_time_val_add() */
            stun->next_tick = now + timeout * 1000;
            remaining++;
            break;
          default:
            g_assert_not_reached();
            break;
        }
      j = next;
      index++;
    }

    if (remaining > 0)
      keep_timer_going = TRUE;
    else {
      nice_address_to_string (&p->local->addr, tmpbuf1);
      nice_address_to_string (&p->remote->addr, tmpbuf2);
      nice_debug ("Agent %p : Retransmissions failed, giving up on pair %p",
          agent, p);
      nice_debug ("Agent %p : Failed pair is [%s]:%u --> [%s]:%u", agent,
          tmpbuf1, nice_address_get_port (&p->local->addr),
          tmpbuf2, nice_address_get_port (&p->remote->addr));
      candidate_check_pair_fail (stream, agent, p);
      priv_print_conn_check_lists (agent, G_STRFUNC,
          ", retransmission failed");

      /* perform a check if a transition state from connected to
       * ready can be performed. This may happen here, when the last
       * in-progress pair has expired its retransmission count
       * in priv_conn_check_tick_stream(), which is a condition to
       * make the transition connected to ready.
       */
      conn_check_update_check_list_state_for_ready (agent, stream, component);
    }
  }

  /* step: perform an ordinary check, ICE spec, 5.8 "Scheduling Checks"
   * note: This code is executed when the triggered checks list is
   * empty, and when no STUN message has been sent (pacing constraint)
   */
  pair = priv_conn_check_find_next_waiting (stream->conncheck_list);
  if (pair) {
    priv_print_conn_check_lists (agent, G_STRFUNC,
        ", got a pair in Waiting state");
    priv_conn_check_initiate (agent, pair);
    return TRUE;
  }

  /* note: this is unclear in the ICE spec, but a check list in Frozen
   * state (where all pairs are in Frozen state) is not supposed to
   * change its state by an ordinary check, but only by the success of
   * checks in other check lists, in priv_conn_check_unfreeze_related().
   * The underlying idea is to concentrate the checks on a single check
   * list initially.
   */
  if (priv_is_checklist_frozen (stream))
    return keep_timer_going;

  /* step: ordinary check continued, if there's no pair in the waiting
   * state, pick a pair in the frozen state
   */
  pair = priv_conn_check_find_next_frozen (stream->conncheck_list);
  if (pair) {
    priv_print_conn_check_lists (agent, G_STRFUNC,
        ", got a pair in Frozen state");
    SET_PAIR_STATE (agent, pair, NICE_CHECK_WAITING);
    priv_conn_check_initiate (agent, pair);
    return TRUE;
  }
  return keep_timer_going;
}

static gboolean
priv_conn_check_tick_stream_nominate (NiceStream *stream, NiceAgent *agent)
{
  gboolean keep_timer_going = FALSE;
  /* s_xxx counters are stream-wide */
  guint s_inprogress = 0;
  guint s_succeeded = 0;
  guint s_discovered = 0;
  guint s_nominated = 0;
  guint s_waiting_for_nomination = 0;
  guint s_valid = 0;
  guint s_frozen = 0;
  guint s_waiting = 0;
  CandidateCheckPair *other_stream_pair = NULL;
  GSList *i, *j;

  /* Search for a nominated pair (or selected to be nominated pair)
   * from another stream.
   */
  for (i = agent->streams; i ; i = i->next) {
    NiceStream *s = i->data;
    if (s->id == stream->id)
      continue;
    for (j = s->conncheck_list; j ; j = j->next) {
      CandidateCheckPair *p = j->data;
      if (p->nominated || (p->use_candidate_on_next_check &&
          p->state != NICE_CHECK_FAILED)) {
        other_stream_pair = p;
        break;
      }
    }
    if (other_stream_pair)
      break;
  }

  /* we compute some stream-wide counter values */
  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_FROZEN)
      s_frozen++;
    else if (p->state == NICE_CHECK_IN_PROGRESS)
      s_inprogress++;
    else if (p->state == NICE_CHECK_WAITING)
      s_waiting++;
    else if (p->state == NICE_CHECK_SUCCEEDED)
      s_succeeded++;
    else if (p->state == NICE_CHECK_DISCOVERED)
      s_discovered++;
    if (p->valid)
      s_valid++;

    if ((p->state == NICE_CHECK_SUCCEEDED || p->state == NICE_CHECK_DISCOVERED)
        && p->nominated)
      s_nominated++;
    else if ((p->state == NICE_CHECK_SUCCEEDED ||
            p->state == NICE_CHECK_DISCOVERED) && !p->nominated)
      s_waiting_for_nomination++;
  }

  /* note: keep the timer going as long as there is work to be done */
  if (s_inprogress)
    keep_timer_going = TRUE;
  
  if (s_nominated < stream->n_components &&
      s_waiting_for_nomination) {
    if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent)) {
      if (agent->nomination_mode == NICE_NOMINATION_MODE_REGULAR &&
          agent->controlling_mode) {
#define NICE_MIN_NUMBER_OF_VALID_PAIRS 2
        /* ICE 8.1.1.1 Regular nomination
         * we choose to nominate the valid pair of a component if
         * - there is no pair left frozen, waiting or in-progress, or
         * - if there are at least two valid pairs, or
         * - if there is at least one valid pair of type HOST-HOST
         *
         * This is the "stopping criterion" described in 8.1.1.1, and is
         * a "local optimization" between accumulating more valid pairs,
         * and limiting the time spent waiting for in-progress connections
         * checks until they finally fail.
         */
        for (i = stream->components; i; i = i->next) {
          NiceComponent *component = i->data;
          CandidateCheckPair *other_component_pair = NULL;
          CandidateCheckPair *this_component_pair = NULL;
          NiceCandidate *lcand1 = NULL;
          NiceCandidate *rcand1 = NULL;
          NiceCandidate *lcand2, *rcand2;
          gboolean already_done = FALSE;
          gboolean found_other_component_pair = FALSE;
          gboolean found_other_stream_pair = FALSE;
          gboolean first_nomination = FALSE;
          gboolean stopping_criterion;
          /* p_xxx counters are component-wide */
          guint p_valid = 0;
          guint p_frozen = 0;
          guint p_waiting = 0;
          guint p_inprogress = 0;
          guint p_host_host_valid = 0;

          /* we compute some component-wide counter values */
          for (j = stream->conncheck_list; j ; j = j->next) {
            CandidateCheckPair *p = j->data;
            if (p->component_id == component->id) {
              /* verify that the choice of the pair to be nominated
               * has not already been done
               */
              if (p->use_candidate_on_next_check)
                already_done = TRUE;
              if (p->state == NICE_CHECK_FROZEN)
                p_frozen++;
              else if (p->state == NICE_CHECK_WAITING)
                p_waiting++;
              else if (p->state == NICE_CHECK_IN_PROGRESS)
                p_inprogress++;
              if (p->valid)
                p_valid++;
              if (p->valid &&
                  p->local->type == NICE_CANDIDATE_TYPE_HOST &&
                  p->remote->type == NICE_CANDIDATE_TYPE_HOST)
                p_host_host_valid++;
            }
          }

          if (already_done)
            continue;

          /* Search for a nominated pair (or selected to be nominated pair)
           * from another component of this stream.
           */
          for (j = stream->conncheck_list; j ; j = j->next) {
            CandidateCheckPair *p = j->data;
            if (p->component_id == component->id)
              continue;
            if (p->nominated || (p->use_candidate_on_next_check &&
                p->state != NICE_CHECK_FAILED)) {
              other_component_pair = p;
              break;
            }
          }

          if (other_stream_pair == NULL && other_component_pair == NULL)
            first_nomination = TRUE;

          /* We choose a pair to be nominated in the list of valid
           * pairs.
           *
           * this pair will be the one with the highest priority,
           * when we don't have other nominated pairs in other
           * components and in other streams
           *
           * this pair will be a pair compatible with another nominated
           * pair from another component if we found one.
           *
           * else this pair will be a pair compatible with another
           * nominated pair from another stream if we found one.
           *
           */
          for (j = stream->conncheck_list; j ; j = j->next) {
            CandidateCheckPair *p = j->data;
            /* note: highest priority item selected (list always sorted) */
            if (p->component_id == component->id &&
                !p->nominated &&
                !p->use_candidate_on_next_check &&
                p->valid) {
              /* According a ICE spec, sect 8.1.1.1.  "Regular
               * Nomination", we enqueue the check that produced this
               * valid pair. When this pair has been discovered, we want
               * to test its parent pair instead.
               */
              if (p->succeeded_pair != NULL) {
                g_assert_cmpint (p->state, ==, NICE_CHECK_DISCOVERED);
                p = p->succeeded_pair;
              }
              g_assert_cmpint (p->state, ==, NICE_CHECK_SUCCEEDED);

              if (this_component_pair == NULL)
                /* highest priority pair */
                this_component_pair = p;

              lcand1 = p->local;
              rcand1 = p->remote;

              if (first_nomination)
                /* use the highest priority pair */
                break;

              if (other_component_pair) {
                lcand2 = other_component_pair->local;
                rcand2 = other_component_pair->remote;
              }
              if (other_component_pair &&
                  lcand1->transport == lcand2->transport &&
                  nice_address_equal_no_port (&lcand1->addr, &lcand2->addr) &&
                  nice_address_equal_no_port (&rcand1->addr, &rcand2->addr)) {
                /* else continue the research with lower priority
                 * pairs, compatible with a nominated pair of
                 * another component
                 */
                this_component_pair = p;
                found_other_component_pair = TRUE;
                break;
              }

              if (other_stream_pair) {
                lcand2 = other_stream_pair->local;
                rcand2 = other_stream_pair->remote;
              }
              if (other_stream_pair &&
                  other_component_pair == NULL &&
                  lcand1->transport == lcand2->transport &&
                  nice_address_equal_no_port (&lcand1->addr, &lcand2->addr) &&
                  nice_address_equal_no_port (&rcand1->addr, &rcand2->addr)) {
                /* else continue the research with lower priority
                 * pairs, compatible with a nominated pair of
                 * another stream
                 */
                this_component_pair = p;
                found_other_stream_pair = TRUE;
                break;
              }
            }
          }

          /* No valid pair for this component */
          if (this_component_pair == NULL)
            continue;

          /* The stopping criterion tries to select a set of pairs of
           * the same kind (transport/type) for all components of a
           * stream, and for all streams, when possible (see last
           * paragraph).
           *
           * When no stream has nominated a pair yet, we apply the
           * following criterion :
           *   - stop if we have a valid host-host pair
           *   - or stop if we have at least "some* (2 in the current
           *     implementation) valid pairs, and select the best one
           *   - or stop if the conncheck cannot evolve more
           *
           * Else when the stream has a nominated pair in another
           * component we apply this criterion:
           *   - stop if we have a valid pair of the same kind than this
           *     other nominated pair.
           *   - or stop if the conncheck cannot evolve more
           *
           * Else when another stream has a nominated pair we apply the
           * following criterion:
           *   - stop if we have a valid pair of the same kind than the
           *     other nominated pair.
           *   - or stop if the conncheck cannot evolve more
           *
           * When no further evolution of the conncheck is possible, we
           * prefer to select the best valid pair we have, *even* if it
           * is not compatible with the transport of another stream of
           * component. We think it's still a better choice than marking
           * this component 'failed'.
           */
          stopping_criterion = FALSE;
          if (first_nomination && p_host_host_valid > 0) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "valid host-host pair", agent);
          } else if (first_nomination &&
              p_valid >= NICE_MIN_NUMBER_OF_VALID_PAIRS) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "*some* valid pairs", agent);
          } else if (found_other_component_pair) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "matching pair in another component", agent);
          } else if (found_other_stream_pair) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "matching pair in another stream", agent);
          } else if (p_waiting == 0 && p_inprogress == 0 && p_frozen == 0) {
            stopping_criterion = TRUE;
            nice_debug ("Agent %p : stopping criterion: "
                "no more pairs to check", agent);
          }

          if (!stopping_criterion)
            continue;

          /* when the stopping criterion is reached, we add the
           * selected pair for this component to the triggered checks
           * list
           */
          nice_debug ("Agent %p : restarting check of %s:%s pair %p with "
              "USE-CANDIDATE attrib (regular nomination) for "
              "stream %d component %d", agent,
              priv_candidate_transport_to_string (
                  this_component_pair->local->transport),
              priv_candidate_transport_to_string (
                  this_component_pair->remote->transport),
              this_component_pair, stream->id, component->id);
          this_component_pair->use_candidate_on_next_check = TRUE;
          priv_add_pair_to_triggered_check_queue (agent, this_component_pair);
          keep_timer_going = TRUE;
        }
      }
    } else if (agent->controlling_mode) {
      for (i = stream->components; i; i = i->next) {
        NiceComponent *component = i->data;

	for (j = stream->conncheck_list; j ; j = j->next) {
	  CandidateCheckPair *p = j->data;
	  /* note: highest priority item selected (list always sorted) */
	  if (p->component_id == component->id &&
              (p->state == NICE_CHECK_SUCCEEDED ||
               p->state == NICE_CHECK_DISCOVERED)) {
	    nice_debug ("Agent %p : restarting check of pair %p as the "
                "nominated pair.", agent, p);
	    p->nominated = TRUE;
            conn_check_update_selected_pair (agent, component, p);
            priv_add_pair_to_triggered_check_queue (agent, p);
            keep_timer_going = TRUE;
	    break; /* move to the next component */
	  }
	}
      }
    }
  }
  if (stream->tick_counter++ % 50 == 0)
    nice_debug ("Agent %p : stream %u: timer tick #%u: %u frozen, "
        "%u in-progress, %u waiting, %u succeeded, %u discovered, "
        "%u nominated, %u waiting-for-nom, %u valid",
        agent, stream->id, stream->tick_counter,
        s_frozen, s_inprogress, s_waiting, s_succeeded, s_discovered,
        s_nominated, s_waiting_for_nomination, s_valid);

  return keep_timer_going;

}

static void
conn_check_stop (NiceAgent *agent)
{
  if (agent->conncheck_timer_source == NULL)
    return;

  g_source_destroy (agent->conncheck_timer_source);
  g_source_unref (agent->conncheck_timer_source);
  agent->conncheck_timer_source = NULL;
  agent->conncheck_ongoing_idle_delay = 0;
}


/*
 * Timer callback that handles initiating and managing connectivity
 * checks (paced by the Ta timer).
 *
 * This function is designed for the g_timeout_add() interface.
 *
 * @return will return FALSE when no more pending timers.
 */
static gboolean priv_conn_check_tick_agent_locked (NiceAgent *agent,
    gpointer user_data)
{
  CandidateCheckPair *pair = NULL;
  gboolean keep_timer_going = FALSE;
  GSList *i, *j;

  /* configure the initial state of the check lists of the agent
   * as described in ICE spec, 5.7.4
   *
   * if all pairs in all check lists are in frozen state, then
   * we are in the initial state (5.7.4, point 1.)
   */
  if (priv_number_of_active_check_lists (agent) == 0) {
    /* set some pairs of the first stream in the waiting state
     * ICE spec, 5.7.4, point 2.
     *
     * note: we adapt the ICE spec here, by selecting the first
     * frozen check list, which is not necessarily the check
     * list of the first stream (the first stream may be completed)
     */
    NiceStream *stream = priv_find_first_frozen_check_list (agent);
    if (stream)
      priv_conn_check_unfreeze_next (agent, stream);
  }

  /* step: perform a test from the triggered checks list,
   * ICE spec, 5.8 "Scheduling Checks"
   */
  pair = priv_get_pair_from_triggered_check_queue (agent);

  if (pair) {
    priv_print_conn_check_lists (agent, G_STRFUNC,
        ", got a pair from triggered check list");
    if (conn_check_send (agent, pair)) {
      SET_PAIR_STATE (agent, pair, NICE_CHECK_FAILED);
      return FALSE;
    }
    return TRUE;
  }

  /* step: process ongoing STUN transactions and
   * perform an ordinary check, ICE spec, 5.8, "Scheduling Checks"
   */
  for (i = agent->streams; i ; i = i->next) {
    NiceStream *stream = i->data;
    if (priv_conn_check_tick_stream (stream, agent))
      keep_timer_going = TRUE;
    if (priv_conn_check_tick_stream_nominate (stream, agent))
      keep_timer_going = TRUE;
  }

  /* step: if no work left and a conncheck list of a stream is still
   * frozen, set the pairs to waiting, according to ICE SPEC, sect
   * 7.1.3.3.  "Check List and Timer State Updates"
   */
  if (!keep_timer_going) {
    for (i = agent->streams; i ; i = i->next) {
      NiceStream *stream = i->data;
      if (priv_is_checklist_frozen (stream)) {
        nice_debug ("Agent %p : stream %d conncheck list is still "
            "frozen, while other lists are completed. Unfreeze it.",
            agent, stream->id);
        keep_timer_going = priv_conn_check_unfreeze_next (agent, stream);
      }
      if (!keep_timer_going && !stream->peer_gathering_done) {
        keep_timer_going = TRUE;
      }
    }
  }

  /* note: we provide a grace period before declaring a component as
   * failed. Components marked connected, and then ready follow another
   * code path, and are not concerned by this grace period.
   */
  if (!keep_timer_going && agent->conncheck_ongoing_idle_delay == 0)
    nice_debug ("Agent %p : waiting %d msecs before checking "
        "for failed components.", agent, agent->idle_timeout);

  if (keep_timer_going)
    agent->conncheck_ongoing_idle_delay = 0;
  else
    agent->conncheck_ongoing_idle_delay += agent->timer_ta;

  /* step: stop timer if no work left */
  if (!keep_timer_going &&
      agent->conncheck_ongoing_idle_delay >= agent->idle_timeout) {
    nice_debug ("Agent %p : checking for failed components now.", agent);
    for (i = agent->streams; i; i = i->next) {
      NiceStream *stream = i->data;
      priv_update_check_list_failed_components (agent, stream);
      for (j = stream->components; j; j = j->next) {
        NiceComponent *component = j->data;
        conn_check_update_check_list_state_for_ready (agent, stream, component);
      }
    }

    nice_debug ("Agent %p : %s: stopping conncheck timer", agent, G_STRFUNC);
    priv_print_conn_check_lists (agent, G_STRFUNC,
        ", conncheck timer stopped");

    /* Stopping the timer so destroy the source.. this will allow
       the timer to be reset if we get a set_remote_candidates after this
       point */
    conn_check_stop (agent);

    /* XXX: what to signal, is all processing now really done? */
    nice_debug ("Agent %p : changing conncheck state to COMPLETED.", agent);
    return FALSE;
  }

  return TRUE;
}

static gboolean priv_conn_keepalive_retransmissions_tick_agent_locked (
    NiceAgent *agent, gpointer pointer)
{
  CandidatePair *pair = (CandidatePair *) pointer;

  g_source_destroy (pair->keepalive.tick_source);
  g_source_unref (pair->keepalive.tick_source);
  pair->keepalive.tick_source = NULL;

  switch (stun_timer_refresh (&pair->keepalive.timer)) {
    case STUN_USAGE_TIMER_RETURN_TIMEOUT:
      {
        /* Time out */
        StunTransactionId id;
        NiceComponent *component;

        if (!agent_find_component (agent,
                pair->keepalive.stream_id, pair->keepalive.component_id,
                NULL, &component)) {
          nice_debug ("Could not find stream or component in"
              " priv_conn_keepalive_retransmissions_tick");
          return FALSE;
        }

        stun_message_id (&pair->keepalive.stun_message, id);
        stun_agent_forget_transaction (&component->stun_agent, id);
        pair->keepalive.stun_message.buffer = NULL;

        if (agent->media_after_tick) {
          nice_debug ("Agent %p : Keepalive conncheck timed out!! "
              "but media was received. Suspecting keepalive lost because of "
              "network bottleneck", agent);
        } else {
          nice_debug ("Agent %p : Keepalive conncheck timed out!! "
              "peer probably lost connection", agent);
          agent_signal_component_state_change (agent,
              pair->keepalive.stream_id, pair->keepalive.component_id,
              NICE_COMPONENT_STATE_FAILED);
        }
        break;
      }
    case STUN_USAGE_TIMER_RETURN_RETRANSMIT:
      /* Retransmit */
      agent_socket_send (pair->local->sockptr, &pair->remote->addr,
          stun_message_length (&pair->keepalive.stun_message),
          (gchar *)pair->keepalive.stun_buffer);

      nice_debug ("Agent %p : Retransmitting keepalive conncheck",
          agent);
      agent_timeout_add_with_context (agent,
          &pair->keepalive.tick_source,
          "Pair keepalive", stun_timer_remainder (&pair->keepalive.timer),
          priv_conn_keepalive_retransmissions_tick_agent_locked, pair);
      break;
    case STUN_USAGE_TIMER_RETURN_SUCCESS:
      agent_timeout_add_with_context (agent,
          &pair->keepalive.tick_source,
          "Pair keepalive", stun_timer_remainder (&pair->keepalive.timer),
          priv_conn_keepalive_retransmissions_tick_agent_locked, pair);
      break;
    default:
      g_assert_not_reached();
      break;
  }

  return FALSE;
}

static guint32 peer_reflexive_candidate_priority (NiceAgent *agent,
    NiceCandidate *local_candidate)
{
  NiceCandidate *candidate_priority =
      nice_candidate_new (NICE_CANDIDATE_TYPE_PEER_REFLEXIVE);
  guint32 priority;

  candidate_priority->transport = local_candidate->transport;
  candidate_priority->component_id = local_candidate->component_id;
  candidate_priority->base_addr = local_candidate->addr;
  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE) {
    priority = nice_candidate_jingle_priority (candidate_priority);
  } else if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
             agent->compatibility == NICE_COMPATIBILITY_OC2007) {
    priority = nice_candidate_msn_priority (candidate_priority);
  } else if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
    priority = nice_candidate_ms_ice_priority (candidate_priority,
        agent->reliable, FALSE);
  } else {
    priority = nice_candidate_ice_priority (candidate_priority,
        agent->reliable, FALSE);
  }
  nice_candidate_free (candidate_priority);

  return priority;
}

/* Returns the priority of a local candidate of type peer-reflexive that
 * would be learned as a consequence of a check from this local
 * candidate. See RFC 5245, section 7.1.2.1. "PRIORITY and USE-CANDIDATE".
 * RFC 5245 is more explanatory than RFC 8445 on this detail.
 *
 * Apply to local candidates of type host only, because candidates of type
 * relay are supposed to have a public IP address, that wont generate
 * a peer-reflexive address. Server-reflexive candidates are not
 * concerned too, because no STUN request is sent with a local candidate
 * of this type.
 */
static guint32 stun_request_priority (NiceAgent *agent,
    NiceCandidate *local_candidate)
{
  if (local_candidate->type == NICE_CANDIDATE_TYPE_HOST)
    return peer_reflexive_candidate_priority (agent, local_candidate);
  else
    return local_candidate->priority;
}

static void ms_ice2_legacy_conncheck_send(StunMessage *msg, NiceSocket *sock,
    const NiceAddress *remote_addr)
{
  uint32_t *fingerprint_attr;
  uint32_t fingerprint_orig;
  uint16_t fingerprint_len;
  size_t buffer_len;

  if (msg->agent->ms_ice2_send_legacy_connchecks == FALSE) {
    return;
  }

  fingerprint_attr = (uint32_t *)stun_message_find (msg,
      STUN_ATTRIBUTE_FINGERPRINT, &fingerprint_len);

  if (fingerprint_attr == NULL) {
    nice_debug ("FINGERPRINT not found.");
    return;
  }

  if (fingerprint_len != sizeof (fingerprint_orig)) {
    nice_debug ("Unexpected FINGERPRINT length %u.", fingerprint_len);
    return;
  }

  memcpy (&fingerprint_orig, fingerprint_attr, sizeof (fingerprint_orig));

  buffer_len = stun_message_length (msg);

  *fingerprint_attr = stun_fingerprint (msg->buffer, buffer_len, TRUE);

  agent_socket_send (sock, remote_addr, buffer_len, (gchar *)msg->buffer);

  memcpy (fingerprint_attr, &fingerprint_orig, sizeof (fingerprint_orig));
}

/*
 * Timer callback that handles initiating and managing connectivity
 * checks (paced by the Ta timer).
 *
 * This function is designed for the g_timeout_add() interface.
 *
 * @return will return FALSE when no more pending timers.
 */
static gboolean priv_conn_keepalive_tick_unlocked (NiceAgent *agent)
{
  GSList *i, *j, *k;
  int errors = 0;
  size_t buf_len = 0;
  guint64 now;
  guint64 min_next_tick;
  guint64 next_timer_tick;

  now = g_get_monotonic_time ();
  min_next_tick = now + 1000 * NICE_AGENT_TIMER_TR_DEFAULT;

  /* case 1: session established and media flowing
   *         (ref ICE sect 11 "Keepalives" RFC-8445)
   * TODO: keepalives should be send only when no packet has been sent
   * on that pair in the last Tr seconds, and not unconditionally.
   */
  for (i = agent->streams; i; i = i->next) {

    NiceStream *stream = i->data;
    for (j = stream->components; j; j = j->next) {
      NiceComponent *component = j->data;
      if (component->selected_pair.local != NULL) {
	CandidatePair *p = &component->selected_pair;

        /* Disable keepalive checks on TCP candidates unless explicitly enabled */
        if (p->local->transport != NICE_CANDIDATE_TRANSPORT_UDP &&
            !agent->keepalive_conncheck)
          continue;

        if (p->keepalive.next_tick) {
          if (p->keepalive.next_tick < min_next_tick)
            min_next_tick = p->keepalive.next_tick;
          if (now < p->keepalive.next_tick)
            continue;
        }

        if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE ||
            agent->keepalive_conncheck) {
          uint8_t uname[NICE_STREAM_MAX_UNAME];
          size_t uname_len =
              priv_create_username (agent, agent_find_stream (agent, stream->id),
                  component->id, p->remote, p->local, uname, sizeof (uname),
                  FALSE);
          uint8_t *password = NULL;
          size_t password_len = priv_get_password (agent,
              agent_find_stream (agent, stream->id), p->remote, &password);

          if (p->keepalive.stun_message.buffer != NULL) {
            nice_debug ("Agent %p: Keepalive for s%u:c%u still"
                " retransmitting, not restarting", agent, stream->id,
                component->id);
            continue;
          }

          if (nice_debug_is_enabled ()) {
            gchar tmpbuf[INET6_ADDRSTRLEN];
            nice_address_to_string (&p->remote->addr, tmpbuf);
            nice_debug ("Agent %p : Keepalive STUN-CC REQ to '%s:%u', "
                "(c-id:%u), username='%.*s' (%" G_GSIZE_FORMAT "), "
                "password='%.*s' (%" G_GSIZE_FORMAT "), priority=%08x.",
                agent, tmpbuf, nice_address_get_port (&p->remote->addr),
                component->id, (int) uname_len, uname, uname_len,
                (int) password_len, password, password_len,
                p->stun_priority);
          }
          if (uname_len > 0) {
            buf_len = stun_usage_ice_conncheck_create (&component->stun_agent,
                &p->keepalive.stun_message, p->keepalive.stun_buffer,
                sizeof(p->keepalive.stun_buffer),
                uname, uname_len, password, password_len,
                agent->controlling_mode, agent->controlling_mode,
                p->stun_priority,
                agent->tie_breaker,
                NULL,
                agent_to_ice_compatibility (agent));

            nice_debug ("Agent %p: conncheck created %zd - %p",
                agent, buf_len, p->keepalive.stun_message.buffer);

            if (buf_len > 0) {
              stun_timer_start (&p->keepalive.timer,
                  agent->stun_initial_timeout,
                  agent->stun_max_retransmissions);

              agent->media_after_tick = FALSE;

              /* send the conncheck */
              agent_socket_send (p->local->sockptr, &p->remote->addr,
                  buf_len, (gchar *)p->keepalive.stun_buffer);

              p->keepalive.stream_id = stream->id;
              p->keepalive.component_id = component->id;
              p->keepalive.next_tick = now + 1000 * NICE_AGENT_TIMER_TR_DEFAULT;

              agent_timeout_add_with_context (agent,
                  &p->keepalive.tick_source, "Pair keepalive",
                  stun_timer_remainder (&p->keepalive.timer),
                  priv_conn_keepalive_retransmissions_tick_agent_locked, p);

              next_timer_tick = now + agent->timer_ta * 1000;
              goto done;
            } else {
              ++errors;
            }
          }
        } else {
          buf_len = stun_usage_bind_keepalive (&component->stun_agent,
              &p->keepalive.stun_message, p->keepalive.stun_buffer,
              sizeof(p->keepalive.stun_buffer));

          if (buf_len > 0) {
            agent_socket_send (p->local->sockptr, &p->remote->addr, buf_len,
                (gchar *)p->keepalive.stun_buffer);

            p->keepalive.next_tick = now + 1000 * NICE_AGENT_TIMER_TR_DEFAULT;

            if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
              ms_ice2_legacy_conncheck_send (&p->keepalive.stun_message,
                  p->local->sockptr, &p->remote->addr);
            }

            if (nice_debug_is_enabled ()) {
              gchar tmpbuf[INET6_ADDRSTRLEN];
              nice_address_to_string (&p->local->base_addr, tmpbuf);
              nice_debug ("Agent %p : resending STUN to keep the "
                  "selected base address %s:%u alive in s%d/c%d.", agent,
                  tmpbuf, nice_address_get_port (&p->local->base_addr),
                  stream->id, component->id);
            }

            next_timer_tick = now + agent->timer_ta * 1000;
            goto done;
          } else {
            ++errors;
          }
        }
      }
    }
  }

  /* case 2: connectivity establishment ongoing
   *         (ref ICE sect 5.1.1.4 "Keeping Candidates Alive" RFC-8445)
   */
  for (i = agent->streams; i; i = i->next) {
    NiceStream *stream = i->data;
    for (j = stream->components; j; j = j->next) {
      NiceComponent *component = j->data;
      if (component->state < NICE_COMPONENT_STATE_CONNECTED &&
          agent->stun_server_ip) {
        NiceAddress stun_server;
        if (nice_address_set_from_string (&stun_server, agent->stun_server_ip)) {
          StunAgent stun_agent;
          uint8_t stun_buffer[STUN_MAX_MESSAGE_SIZE_IPV6];
          StunMessage stun_message;
          size_t buffer_len = 0;

          nice_address_set_port (&stun_server, agent->stun_server_port);

          nice_agent_init_stun_agent (agent, &stun_agent);

          buffer_len = stun_usage_bind_create (&stun_agent,
              &stun_message, stun_buffer, sizeof(stun_buffer));

          for (k = component->local_candidates; k; k = k->next) {
            NiceCandidate *candidate = (NiceCandidate *) k->data;
            if (candidate->type == NICE_CANDIDATE_TYPE_HOST &&
                candidate->transport == NICE_CANDIDATE_TRANSPORT_UDP &&
                nice_address_ip_version (&candidate->addr) ==
                nice_address_ip_version (&stun_server)) {

              if (candidate->keepalive_next_tick) {
                if (candidate->keepalive_next_tick < min_next_tick)
                  min_next_tick = candidate->keepalive_next_tick;
                if (now < candidate->keepalive_next_tick)
                continue;
              }

              /* send the conncheck */
              if (nice_debug_is_enabled ()) {
                gchar tmpbuf[INET6_ADDRSTRLEN];
                nice_address_to_string (&candidate->addr, tmpbuf);
                nice_debug ("Agent %p : resending STUN to keep the local "
                    "candidate %s:%u alive in s%d/c%d.", agent,
                    tmpbuf, nice_address_get_port (&candidate->addr),
                    stream->id, component->id);
              }
              agent_socket_send (candidate->sockptr, &stun_server,
                  buffer_len, (gchar *)stun_buffer);
              candidate->keepalive_next_tick = now +
                  1000 * NICE_AGENT_TIMER_TR_DEFAULT;
              next_timer_tick = now + agent->timer_ta * 1000;
              goto done;
            }
          }
        }
      }
    }
  }

  next_timer_tick = min_next_tick;

  done:
  if (errors) {
    nice_debug ("Agent %p : %s: stopping keepalive timer", agent, G_STRFUNC);
    return FALSE;
  }

  if (agent->keepalive_timer_source) {
    g_source_destroy (agent->keepalive_timer_source);
    g_source_unref (agent->keepalive_timer_source);
    agent->keepalive_timer_source = NULL;
  }
  agent_timeout_add_with_context (agent, &agent->keepalive_timer_source,
      "Connectivity keepalive timeout", (next_timer_tick - now)/ 1000,
      priv_conn_keepalive_tick_agent_locked, NULL);
  return TRUE;
}

static gboolean priv_conn_keepalive_tick_agent_locked (NiceAgent *agent,
    gpointer pointer)
{
  gboolean ret;

  ret = priv_conn_keepalive_tick_unlocked (agent);
  if (ret == FALSE) {
    if (agent->keepalive_timer_source) {
      g_source_destroy (agent->keepalive_timer_source);
      g_source_unref (agent->keepalive_timer_source);
      agent->keepalive_timer_source = NULL;
    }
  }

  return ret;
}


static gboolean priv_turn_allocate_refresh_retransmissions_tick_agent_locked (
    NiceAgent *agent, gpointer pointer)
{
  CandidateRefresh *cand = (CandidateRefresh *) pointer;

  g_source_destroy (cand->tick_source);
  g_source_unref (cand->tick_source);
  cand->tick_source = NULL;

  switch (stun_timer_refresh (&cand->timer)) {
    case STUN_USAGE_TIMER_RETURN_TIMEOUT:
      {
        /* Time out */
        StunTransactionId id;

        stun_message_id (&cand->stun_message, id);
        stun_agent_forget_transaction (&cand->stun_agent, id);

        refresh_free (agent, cand);
        break;
      }
    case STUN_USAGE_TIMER_RETURN_RETRANSMIT:
      /* Retransmit */
      agent_socket_send (cand->nicesock, &cand->server,
          stun_message_length (&cand->stun_message), (gchar *)cand->stun_buffer);

      agent_timeout_add_with_context (agent, &cand->tick_source,
          "Candidate TURN refresh", stun_timer_remainder (&cand->timer),
          priv_turn_allocate_refresh_retransmissions_tick_agent_locked, cand);
      break;
    case STUN_USAGE_TIMER_RETURN_SUCCESS:
      agent_timeout_add_with_context (agent, &cand->tick_source,
          "Candidate TURN refresh", stun_timer_remainder (&cand->timer),
          priv_turn_allocate_refresh_retransmissions_tick_agent_locked, cand);
      break;
    default:
      /* Nothing to do. */
      break;
  }

  return G_SOURCE_REMOVE;
}

static void priv_turn_allocate_refresh_tick_unlocked (NiceAgent *agent,
    CandidateRefresh *cand)
{
  uint8_t *username;
  gsize username_len;
  uint8_t *password;
  gsize password_len;
  size_t buffer_len = 0;
  StunUsageTurnCompatibility turn_compat =
      agent_to_turn_compatibility (agent);

  username = (uint8_t *)cand->candidate->turn->username;
  username_len = (size_t) strlen (cand->candidate->turn->username);
  password = (uint8_t *)cand->candidate->turn->password;
  password_len = (size_t) strlen (cand->candidate->turn->password);

  if (turn_compat == STUN_USAGE_TURN_COMPATIBILITY_MSN ||
      turn_compat == STUN_USAGE_TURN_COMPATIBILITY_OC2007) {
    username = cand->candidate->turn->decoded_username;
    password = cand->candidate->turn->decoded_password;
    username_len = cand->candidate->turn->decoded_username_len;
    password_len = cand->candidate->turn->decoded_password_len;
  }

  buffer_len = stun_usage_turn_create_refresh (&cand->stun_agent,
      &cand->stun_message,  cand->stun_buffer, sizeof(cand->stun_buffer),
      cand->stun_resp_msg.buffer == NULL ? NULL : &cand->stun_resp_msg, -1,
      username, username_len,
      password, password_len,
      turn_compat);

  nice_debug ("Agent %p : Sending allocate Refresh %zd", agent,
      buffer_len);

  if (cand->tick_source != NULL) {
    g_source_destroy (cand->tick_source);
    g_source_unref (cand->tick_source);
    cand->tick_source = NULL;
  }

  if (buffer_len > 0) {
    stun_timer_start (&cand->timer,
        agent->stun_initial_timeout,
        agent->stun_max_retransmissions);

    /* send the refresh */
    agent_socket_send (cand->nicesock, &cand->server,
        buffer_len, (gchar *)cand->stun_buffer);

    agent_timeout_add_with_context (agent, &cand->tick_source,
        "Candidate TURN refresh", stun_timer_remainder (&cand->timer),
        priv_turn_allocate_refresh_retransmissions_tick_agent_locked, cand);
  }

}


/*
 * Timer callback that handles refreshing TURN allocations
 *
 * This function is designed for the g_timeout_add() interface.
 *
 * @return will return FALSE when no more pending timers.
 */
static gboolean priv_turn_allocate_refresh_tick_agent_locked (NiceAgent *agent,
    gpointer pointer)
{
  CandidateRefresh *cand = (CandidateRefresh *) pointer;

  priv_turn_allocate_refresh_tick_unlocked (agent, cand);

  return G_SOURCE_REMOVE;
}


/*
 * Initiates the next pending connectivity check.
 */
void conn_check_schedule_next (NiceAgent *agent)
{
  if (agent->discovery_unsched_items > 0)
    nice_debug ("Agent %p : WARN: starting conn checks before local candidate gathering is finished.", agent);

  /* step: schedule timer if not running yet */
  if (agent->conncheck_timer_source == NULL) {
    agent_timeout_add_with_context (agent, &agent->conncheck_timer_source,
        "Connectivity check schedule", agent->timer_ta,
        priv_conn_check_tick_agent_locked, NULL);
  }

  /* step: also start the keepalive timer */
  if (agent->keepalive_timer_source == NULL) {
    agent_timeout_add_with_context (agent, &agent->keepalive_timer_source,
        "Connectivity keepalive timeout", agent->timer_ta,
        priv_conn_keepalive_tick_agent_locked, NULL);
  }
}

/*
 * Compares two connectivity check items. Checkpairs are sorted
 * in descending priority order, with highest priority item at
 * the start of the list.
 */
gint conn_check_compare (const CandidateCheckPair *a, const CandidateCheckPair *b)
{
  if (a->priority > b->priority)
    return -1;
  else if (a->priority < b->priority)
    return 1;
  return 0;
}

/* Find a transport compatible with a given socket.
 *
 * Returns TRUE when a matching transport can be guessed from
 * the type of the socket in an unambiguous way.
 */
static gboolean
nice_socket_has_compatible_transport (NiceSocket *socket,
    NiceCandidateTransport *transport)
{
  gboolean found = TRUE;

  g_assert (socket);
  g_assert (transport);

  switch (socket->type) {
    case NICE_SOCKET_TYPE_TCP_BSD:
      if (nice_tcp_bsd_socket_get_passive_parent (socket))
        *transport = NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE;
      else
        *transport = NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE;
      break;
    case NICE_SOCKET_TYPE_TCP_PASSIVE:
      *transport = NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE;
      break;
    case NICE_SOCKET_TYPE_TCP_ACTIVE:
      *transport = NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE;
      break;
    case NICE_SOCKET_TYPE_UDP_BSD:
      *transport = NICE_CANDIDATE_TRANSPORT_UDP;
      break;
    default:
      found = FALSE;
  }

  return found;
}

/* Test if a local socket and a local candidate are compatible. This
 * function does supplementary tests when the address and port are not
 * sufficient to give a unique candidate. We try to avoid comparing
 * directly the sockptr value, when possible, to rely on objective
 * properties of the candidate and the socket instead, and we also
 * choose to ignore the conncheck list for the same reason.
 */
static gboolean
local_candidate_and_socket_compatible (NiceAgent *agent,
    NiceCandidate *lcand, NiceSocket *socket)
{
  gboolean ret = TRUE;
  NiceCandidateTransport transport;

  g_assert (socket);
  g_assert (lcand);

  if (nice_socket_has_compatible_transport (socket, &transport))
    ret = (lcand->transport == transport);
  else if (socket->type == NICE_SOCKET_TYPE_UDP_TURN)
    /* Socket of type udp-turn will match a unique local candidate
     * by its sockptr value. An an udp-turn socket doesn't carry enough
     * information when base socket is udp-turn-over-tcp to disambiguate
     * between a tcp-act and a tcp-pass local candidate.
     */
    ret = (lcand->sockptr == socket);

  return ret;
}

/* Test if a local socket and a remote candidate are compatible.
 * This function is very close to its local candidate counterpart,
 * the difference is that we also use information from the local
 * candidate we may have identified previously. This is needed
 * to disambiguate the transport of the candidate with a socket
 * of type udp-turn.
 *
 */
static gboolean
remote_candidate_and_socket_compatible (NiceAgent *agent,
    NiceCandidate *lcand, NiceCandidate *rcand, NiceSocket *socket)
{
  gboolean ret = TRUE;
  NiceCandidateTransport transport;

  g_assert (socket);
  g_assert (rcand);

  if (nice_socket_has_compatible_transport (socket, &transport))
    ret = (conn_check_match_transport (rcand->transport) == transport);

  /* This supplementary test with the local candidate is needed with
   * socket of type udp-turn, the type doesn't allow to disambiguate
   * between a tcp-pass and a tcp-act remote candidate
   */
  if (lcand && ret)
    ret = (conn_check_match_transport (lcand->transport) == rcand->transport);

  return ret;
}

void
conn_check_remote_candidates_set(NiceAgent *agent, NiceStream *stream,
    NiceComponent *component)
{
  GList *i;
  GSList *j;
  NiceCandidate *lcand = NULL, *rcand = NULL;

  nice_debug ("Agent %p : conn_check_remote_candidates_set %u %u",
    agent, stream->id, component->id);

  if (stream->remote_ufrag[0] == 0)
    return;

  if (component->incoming_checks.head)
    nice_debug ("Agent %p : credentials have been set, "
      "we can process incoming checks", agent);

  for (i = component->incoming_checks.head; i;) {
    IncomingCheck *icheck = i->data;
    GList *i_next = i->next;

    nice_debug ("Agent %p : replaying icheck=%p (sock=%p)",
        agent, icheck, icheck->local_socket);

    /* sect 7.2.1.3., "Learning Peer Reflexive Candidates", has to
     * be handled separately */
    for (j = component->local_candidates; j; j = j->next) {
      NiceCandidate *cand = j->data;
      NiceAddress *addr;

      if (cand->type == NICE_CANDIDATE_TYPE_RELAYED)
        addr = &cand->addr;
      else
        addr = &cand->base_addr;

      if (nice_address_equal (&icheck->local_socket->addr, addr) &&
          local_candidate_and_socket_compatible (agent, cand,
          icheck->local_socket)) {
        lcand = cand;
        break;
      }
    }

    g_assert (lcand != NULL);

    for (j = component->remote_candidates; j; j = j->next) {
      NiceCandidate *cand = j->data;
      if (nice_address_equal (&cand->addr, &icheck->from) &&
          remote_candidate_and_socket_compatible (agent, lcand, cand,
          icheck->local_socket)) {
        rcand = cand;
        break;
      }
    }

    if (lcand->transport == NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE) {
      CandidateCheckPair *pair = NULL;

      for (j = stream->conncheck_list; j; j = j->next) {
        CandidateCheckPair *p = j->data;
        if (lcand == p->local && rcand == p->remote) {
          pair = p;
          break;
        }
      }
      if (pair == NULL) {
        pair = priv_conn_check_add_for_candidate_pair_matched (agent,
            stream->id, component, lcand, rcand, NICE_CHECK_SUCCEEDED);
        if (pair)
          pair->valid = TRUE;
      }
    }

    priv_schedule_triggered_check (agent, stream, component,
        icheck->local_socket, rcand);
    if (icheck->use_candidate)
      priv_mark_pair_nominated (agent, stream, component, lcand, rcand);

    if (icheck->username)
      g_free (icheck->username);
    g_slice_free (IncomingCheck, icheck);
    g_queue_delete_link (&component->incoming_checks, i);
    i = i_next;
  }
}

/*
 * Handle any processing steps for connectivity checks after
 * remote credentials have been set. This function handles
 * the special case where answerer has sent us connectivity
 * checks before the answer (containing credentials information),
 * reaches us. The special case is documented in RFC 5245 sect 7.2.
 * ).
 */
void conn_check_remote_credentials_set(NiceAgent *agent, NiceStream *stream)
{
  GSList *j;

  for (j = stream->components; j ; j = j->next) {
    NiceComponent *component = j->data;

    conn_check_remote_candidates_set(agent, stream, component);
  }
}

/*
 * Enforces the upper limit for connectivity checks by dropping
 * lower-priority pairs as described RFC 8445 section 6.1.2.5. See also
 * conn_check_add_for_candidate().
 * Returns TRUE if the pair in argument is one of the deleted pairs.
 */
static gboolean priv_limit_conn_check_list_size (NiceAgent *agent,
    NiceStream *stream, CandidateCheckPair *pair)
{
  guint valid = 0;
  guint cancelled = 0;
  gboolean deleted = FALSE;
  GSList *item = stream->conncheck_list;

  while (item) {
    CandidateCheckPair *p = item->data;
    GSList *next = item->next;

    valid++;
    /* We remove lower-priority pairs, but only the ones that can be
     * safely discarded without breaking an ongoing conncheck process.
     * This only includes pairs that are in the frozen state (those
     * initially added when remote candidates are received) or in failed
     * state. Pairs in any other state play a role in the conncheck, and
     * there removal may lead to a failing conncheck that would succeed
     * otherwise.
     *
     * We also remove failed pairs from the list unconditionally.
     */
    if ((valid > agent->max_conn_checks && p->state == NICE_CHECK_FROZEN) ||
        p->state == NICE_CHECK_FAILED) {
      if (p == pair)
        deleted = TRUE;
      nice_debug ("Agent %p : pair %p removed.", agent, p);
      candidate_check_pair_free (agent, p);
      stream->conncheck_list = g_slist_delete_link (stream->conncheck_list,
          item);
      cancelled++;
    }
    item = next;
  }

  if (cancelled > 0)
    nice_debug ("Agent %p : Pruned %d pairs. "
        "Conncheck list has %d elements left. "
        "Maximum connchecks allowed : %d", agent, cancelled,
        valid - cancelled, agent->max_conn_checks);

  return deleted;
}

/*
 * Changes the selected pair for the component if 'pair'
 * has higher priority than the currently selected pair. See
 * RFC 8445 sect 8.1.1. "Nominating Pairs"
 */
void
conn_check_update_selected_pair (NiceAgent *agent, NiceComponent *component,
    CandidateCheckPair *pair)
{
  CandidatePair cpair = { 0, };

  g_assert (component);
  g_assert (pair);
  /* pair is expected to have the nominated flag */
  g_assert (pair->nominated);
  if (pair->priority > component->selected_pair.priority) {
    gchar priority[NICE_CANDIDATE_PAIR_PRIORITY_MAX_SIZE];
    nice_candidate_pair_priority_to_string (pair->priority, priority);
    nice_debug ("Agent %p : changing SELECTED PAIR for component %u: %s:%s "
        "(prio:%s).", agent, component->id,
        pair->local->foundation, pair->remote->foundation, priority);

    cpair.local = pair->local;
    cpair.remote = pair->remote;
    cpair.priority = pair->priority;
    cpair.stun_priority = pair->stun_priority;

    nice_component_update_selected_pair (agent, component, &cpair);

    priv_conn_keepalive_tick_unlocked (agent);

    agent_signal_new_selected_pair (agent, pair->stream_id, component->id,
        pair->local, pair->remote);
  }
}

/*
 * Updates the check list state.
 *
 * Implements parts of the algorithm described in 
 * ICE sect 8.1.2. "Updating States" (RFC 5245): if for any
 * component, all checks have been completed and have
 * failed to produce a nominated pair, mark that component's
 * state to NICE_CHECK_FAILED.
 *
 * Sends a component state changesignal via 'agent'.
 */
static void priv_update_check_list_failed_components (NiceAgent *agent, NiceStream *stream)
{
  GSList *i;
  gboolean completed;
  guint nominated;
  /* note: emitting a signal might cause the client 
   *       to remove the stream, thus the component count
   *       must be fetched before entering the loop*/
  guint c, components = stream->n_components;

  if (stream->conncheck_list == NULL)
    return;

  for (i = agent->discovery_list; i; i = i->next) {
    CandidateDiscovery *d = i->data;

    /* There is still discovery ogoing for this stream,
     * so don't fail any of it's candidates.
     */
    if (d->stream_id == stream->id && !d->done)
      return;
  }
  if (agent->discovery_list != NULL)
    return;

  /* note: iterate the conncheck list for each component separately */
  for (c = 0; c < components; c++) {
    NiceComponent *component = NULL;
    if (!agent_find_component (agent, stream->id, c+1, NULL, &component))
      continue;

    nominated = 0;
    completed = TRUE;
    for (i = stream->conncheck_list; i; i = i->next) {
      CandidateCheckPair *p = i->data;

      g_assert_cmpuint (p->stream_id, ==, stream->id);

      if (p->component_id == (c + 1)) {
        if (p->nominated)
          ++nominated;
	if (p->state != NICE_CHECK_FAILED &&
            p->state != NICE_CHECK_SUCCEEDED &&
            p->state != NICE_CHECK_DISCOVERED)
	  completed = FALSE;
      }
    }
 
    /* note: all pairs are either failed or succeeded, and the component
     * has not produced a nominated pair.
     * Set the component to FAILED only if it actually had remote candidates
     * that failed.. */
    if (completed && nominated == 0 &&
        component != NULL && component->remote_candidates != NULL)
      agent_signal_component_state_change (agent,
					   stream->id,
					   (c + 1), /* component-id */
					   NICE_COMPONENT_STATE_FAILED);
  }
}

/*
 * Updates the check list state for a stream component.
 *
 * Implements the algorithm described in ICE sect 8.1.2 
 * "Updating States" (ID-19) as it applies to checks of 
 * a certain component. If there are any nominated pairs, 
 * ICE processing may be concluded, and component state is 
 * changed to READY.
 *
 * Sends a component state changesignal via 'agent'.
 */
void conn_check_update_check_list_state_for_ready (NiceAgent *agent,
    NiceStream *stream, NiceComponent *component)
{
  GSList *i;
  guint valid = 0, nominated = 0;

  g_assert (component);

  /* step: search for at least one nominated pair */
  for (i = stream->conncheck_list; i; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->component_id == component->id) {
      if (p->valid) {
	++valid;
	if (p->nominated == TRUE) {
          ++nominated;
	}
      }
    }
  }

  if (nominated > 0) {
    /* Only go to READY if no checks are left in progress. If there are
     * any that are kept, then this function will be called again when the
     * conncheck tick timer finishes them all */
    if (priv_prune_pending_checks (agent, stream, component) == 0) {
      /* Continue through the states to give client code a nice
       * logical progression. See http://phabricator.freedesktop.org/D218 for
       * discussion. */
      if (component->state < NICE_COMPONENT_STATE_CONNECTING ||
          component->state == NICE_COMPONENT_STATE_FAILED)
        agent_signal_component_state_change (agent, stream->id, component->id,
            NICE_COMPONENT_STATE_CONNECTING);
      if (component->state < NICE_COMPONENT_STATE_CONNECTED)
        agent_signal_component_state_change (agent, stream->id, component->id,
            NICE_COMPONENT_STATE_CONNECTED);
      agent_signal_component_state_change (agent, stream->id,
          component->id, NICE_COMPONENT_STATE_READY);
    }
  }
  nice_debug ("Agent %p : conn.check list status: %u nominated, %u valid, c-id %u.", agent, nominated, valid, component->id);
}

/*
 * The remote party has signalled that the candidate pair
 * described by 'component' and 'remotecand' is nominated
 * for use.
 */
static void priv_mark_pair_nominated (NiceAgent *agent, NiceStream *stream, NiceComponent *component, NiceCandidate *localcand, NiceCandidate *remotecand)
{
  GSList *i;

  g_assert (component);

  if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent) &&
      agent->controlling_mode)
    return;

  /* step: search for at least one nominated pair */
  for (i = stream->conncheck_list; i; i = i->next) {
    CandidateCheckPair *pair = i->data;
    if (pair->local == localcand && pair->remote == remotecand) {
      /* ICE, 7.2.1.5. Updating the Nominated Flag */
      /* note: TCP candidates typically produce peer reflexive
       * candidate, generating a "discovered" pair that can be
       * nominated.
       */
      if (pair->state == NICE_CHECK_SUCCEEDED &&
          pair->discovered_pair != NULL) {
        pair = pair->discovered_pair;
        g_assert_cmpint (pair->state, ==, NICE_CHECK_DISCOVERED);
      }

      /* If the state of this pair is In-Progress, [...] the resulting
       * valid pair has its nominated flag set when the response
       * arrives.
       */
      if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent) &&
          pair->state == NICE_CHECK_IN_PROGRESS) {
        pair->mark_nominated_on_response_arrival = TRUE;
        nice_debug ("Agent %p : pair %p (%s) is in-progress, "
            "will be nominated on response receipt.",
            agent, pair, pair->foundation);
      }

      if (pair->valid ||
          !NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent)) {
        nice_debug ("Agent %p : marking pair %p (%s) as nominated",
            agent, pair, pair->foundation);
        pair->nominated = TRUE;
      }

      if (pair->valid) {
        /* Do not step down to CONNECTED if we're already at state READY*/
        if (component->state == NICE_COMPONENT_STATE_FAILED)
          agent_signal_component_state_change (agent,
              stream->id, component->id, NICE_COMPONENT_STATE_CONNECTING);
        conn_check_update_selected_pair (agent, component, pair);
        if (component->state == NICE_COMPONENT_STATE_CONNECTING)
          /* step: notify the client of a new component state (must be done
           *       before the possible check list state update step */
          agent_signal_component_state_change (agent,
              stream->id, component->id, NICE_COMPONENT_STATE_CONNECTED);
      }

      if (pair->nominated)
        conn_check_update_check_list_state_for_ready (agent, stream, component);
    }
  }
}

/*
 * Creates a new connectivity check pair and adds it to
 * the agent's list of checks.
 */
static CandidateCheckPair *priv_add_new_check_pair (NiceAgent *agent,
    guint stream_id, NiceComponent *component, NiceCandidate *local,
    NiceCandidate *remote, NiceCheckState initial_state)
{
  NiceStream *stream;
  CandidateCheckPair *pair;
  guint64 priority;

  g_assert (local != NULL);
  g_assert (remote != NULL);

  priority = agent_candidate_pair_priority (agent, local, remote);

  if (component->selected_pair.priority &&
      priority < component->selected_pair.priority) {
    gchar prio1[NICE_CANDIDATE_PAIR_PRIORITY_MAX_SIZE];
    gchar prio2[NICE_CANDIDATE_PAIR_PRIORITY_MAX_SIZE];

    nice_candidate_pair_priority_to_string (priority, prio1);
    nice_candidate_pair_priority_to_string (component->selected_pair.priority,
        prio2);
    nice_debug ("Agent %p : do not create a pair that would have a priority "
        "%s lower than selected pair priority %s.", agent, prio1, prio2);
    return NULL;
  }

  stream = agent_find_stream (agent, stream_id);
  pair = g_slice_new0 (CandidateCheckPair);

  pair->stream_id = stream_id;
  pair->component_id = component->id;;
  pair->local = local;
  pair->remote = remote;
  /* note: we use the remote sockptr only in the case
   * of TCP transport
   */
  if (local->transport == NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE &&
      remote->type == NICE_CANDIDATE_TYPE_PEER_REFLEXIVE)
    pair->sockptr = (NiceSocket *) remote->sockptr;
  else
    pair->sockptr = (NiceSocket *) local->sockptr;
  g_snprintf (pair->foundation, NICE_CANDIDATE_PAIR_MAX_FOUNDATION, "%s:%s", local->foundation, remote->foundation);

  pair->priority = agent_candidate_pair_priority (agent, local, remote);
  nice_debug ("Agent %p : creating a new pair", agent);
  SET_PAIR_STATE (agent, pair, initial_state);
  {
      gchar tmpbuf1[INET6_ADDRSTRLEN];
      gchar tmpbuf2[INET6_ADDRSTRLEN];
      nice_address_to_string (&pair->local->addr, tmpbuf1);
      nice_address_to_string (&pair->remote->addr, tmpbuf2);
      nice_debug ("Agent %p : new pair %p : [%s]:%u --> [%s]:%u", agent, pair,
          tmpbuf1, nice_address_get_port (&pair->local->addr),
          tmpbuf2, nice_address_get_port (&pair->remote->addr));
  }
  pair->stun_priority = stun_request_priority (agent, local);

  stream->conncheck_list = g_slist_insert_sorted (stream->conncheck_list, pair,
      (GCompareFunc)conn_check_compare);

  nice_debug ("Agent %p : added a new pair %p with foundation '%s' and "
      "transport %s:%s to stream %u component %u",
      agent, pair, pair->foundation,
      priv_candidate_transport_to_string (pair->local->transport),
      priv_candidate_transport_to_string (pair->remote->transport),
      stream_id, component->id);

  /* If this is the first pair added into the check list and the first stream's
   * components already have valid pairs, unfreeze the pair as it would happen
   * in priv_conn_check_unfreeze_related() were the list not empty. */
  if (stream != agent->streams->data &&
      g_slist_length (stream->conncheck_list) == 1 &&
      priv_all_components_have_valid_pair (agent->streams->data)) {
    nice_debug ("Agent %p : %p is the first pair in this stream's check list "
        "and the first stream already has valid pairs. Unfreezing immediately.",
        agent, pair);
    priv_conn_check_unfreeze_next (agent, stream);
  }

  /* implement the hard upper limit for number of
     checks (see sect 5.7.3 ICE ID-19): */
  if (agent->compatibility == NICE_COMPATIBILITY_RFC5245) {
    if (priv_limit_conn_check_list_size (agent, stream, pair))
      return NULL;
  }

  return pair;
}

NiceCandidateTransport
conn_check_match_transport (NiceCandidateTransport transport)
{
  switch (transport) {
    case NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE:
      return NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE;
      break;
    case NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE:
      return NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE;
      break;
    case NICE_CANDIDATE_TRANSPORT_TCP_SO:
    case NICE_CANDIDATE_TRANSPORT_UDP:
    default:
      return transport;
      break;
  }
}

static CandidateCheckPair *priv_conn_check_add_for_candidate_pair_matched (
    NiceAgent *agent, guint stream_id, NiceComponent *component,
     NiceCandidate *local, NiceCandidate *remote, NiceCheckState initial_state)
{
  CandidateCheckPair *pair;

  pair = priv_add_new_check_pair (agent, stream_id, component, local, remote,
      initial_state);
  if (component->state == NICE_COMPONENT_STATE_CONNECTED ||
      component->state == NICE_COMPONENT_STATE_READY) {
    agent_signal_component_state_change (agent,
        stream_id,
        component->id,
        NICE_COMPONENT_STATE_CONNECTED);
  } else {
    agent_signal_component_state_change (agent,
        stream_id,
        component->id,
        NICE_COMPONENT_STATE_CONNECTING);
  }

  return pair;
}

gboolean conn_check_add_for_candidate_pair (NiceAgent *agent,
    guint stream_id, NiceComponent *component, NiceCandidate *local,
    NiceCandidate *remote)
{
  gboolean ret = FALSE;

  g_assert (local != NULL);
  g_assert (remote != NULL);

  /* note: do not create pairs where the local candidate is a srv-reflexive
   * or peer-reflexive (ICE 6.1.2.4. "Pruning the pairs" RFC 8445)
   */
  if ((agent->compatibility == NICE_COMPATIBILITY_RFC5245 ||
      agent->compatibility == NICE_COMPATIBILITY_WLM2009 ||
      agent->compatibility == NICE_COMPATIBILITY_OC2007R2) &&
      (local->type == NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE ||
      local->type == NICE_CANDIDATE_TYPE_PEER_REFLEXIVE)) {
    return FALSE;
  }

  /* note: do not create pairs where local candidate has TCP passive transport
   *       (ice-tcp-13 6.2. "Forming the Check Lists") */
  if (local->transport == NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE) {
    return FALSE;
  }

  /* note: match pairs only if transport and address family are the same */
  if (local->transport == conn_check_match_transport (remote->transport) &&
     local->addr.s.addr.sa_family == remote->addr.s.addr.sa_family) {
    priv_conn_check_add_for_candidate_pair_matched (agent, stream_id, component,
        local, remote, NICE_CHECK_FROZEN);
    ret = TRUE;
  }

  return ret;
}

/*
 * Forms new candidate pairs by matching the new remote candidate
 * 'remote_cand' with all existing local candidates of 'component'.
 * Implements the logic described in ICE sect 5.7.1. "Forming Candidate
 * Pairs" (ID-19).
 *
 * @param agent context
 * @param component pointer to the component
 * @param remote remote candidate to match with
 *
 * @return number of checks added, negative on fatal errors
 */
int conn_check_add_for_candidate (NiceAgent *agent, guint stream_id, NiceComponent *component, NiceCandidate *remote)
{
  GSList *i;
  int added = 0;
  int ret = 0;

  g_assert (remote != NULL);

  /* note: according to 7.2.1.3, "Learning Peer Reflexive Candidates",
   * the agent does not pair this candidate with any local candidates.
   */
  if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent) &&
      remote->type == NICE_CANDIDATE_TYPE_PEER_REFLEXIVE)
  {
    return added;
  }

  for (i = component->local_candidates; i ; i = i->next) {
    NiceCandidate *local = i->data;

    if (agent->force_relay && local->type != NICE_CANDIDATE_TYPE_RELAYED)
        continue;

    ret = conn_check_add_for_candidate_pair (agent, stream_id, component, local, remote);

    if (ret) {
      ++added;
    }
  }

  return added;
}

/*
 * Forms new candidate pairs by matching the new local candidate
 * 'local_cand' with all existing remote candidates of 'component'.
 *
 * @param agent context
 * @param component pointer to the component
 * @param local local candidate to match with
 *
 * @return number of checks added, negative on fatal errors
 */
int conn_check_add_for_local_candidate (NiceAgent *agent, guint stream_id, NiceComponent *component, NiceCandidate *local)
{
  GSList *i;
  int added = 0;
  int ret = 0;

  g_assert (local != NULL);

  /*
   * note: according to 7.1.3.2.1 "Discovering Peer Reflexive
   * Candidates", the peer reflexive candidate is not paired
   * with other remote candidates
   */

  if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent) &&
      local->type == NICE_CANDIDATE_TYPE_PEER_REFLEXIVE)
  {
    return added;
  }

  for (i = component->remote_candidates; i ; i = i->next) {

    NiceCandidate *remote = i->data;
    ret = conn_check_add_for_candidate_pair (agent, stream_id, component, local, remote);

    if (ret) {
      ++added;
    }
  }

  return added;
}

/*
 * Frees the CandidateCheckPair structure pointer to 
 * by 'user data'. Compatible with GDestroyNotify.
 */
static void candidate_check_pair_free (NiceAgent *agent,
    CandidateCheckPair *pair)
{
  priv_remove_pair_from_triggered_check_queue (agent, pair);
  priv_free_all_stun_transactions (pair, NULL);
  g_slice_free (CandidateCheckPair, pair);
}

/*
 * Frees all resources of all connectivity checks.
 */
void conn_check_free (NiceAgent *agent)
{
  GSList *i;
  for (i = agent->streams; i; i = i->next) {
    NiceStream *stream = i->data;

    if (stream->conncheck_list) {
      GSList *item;

      nice_debug ("Agent %p, freeing conncheck_list of stream %p", agent,
          stream);
      for (item = stream->conncheck_list; item; item = item->next)
        candidate_check_pair_free (agent, item->data);
      g_slist_free (stream->conncheck_list);
      stream->conncheck_list = NULL;
    }
  }

  conn_check_stop (agent);
}

/*
 * Prunes the list of connectivity checks for items related
 * to stream 'stream_id'. 
 *
 * @return TRUE on success, FALSE on a fatal error
 */
void conn_check_prune_stream (NiceAgent *agent, NiceStream *stream)
{
  GSList *i;
  gboolean keep_going = FALSE;

  if (stream->conncheck_list) {
    GSList *item;

    nice_debug ("Agent %p, freeing conncheck_list of stream %p", agent, stream);

    for (item = stream->conncheck_list; item; item = item->next)
      candidate_check_pair_free (agent, item->data);
    g_slist_free (stream->conncheck_list);
    stream->conncheck_list = NULL;
  }

  for (i = agent->streams; i; i = i->next) {
    NiceStream *s = i->data;
    if (s->conncheck_list) {
      keep_going = TRUE;
      break;
    }
  }

  if (!keep_going)
    conn_check_stop (agent);
}

/*
 * Fills 'dest' with a username string for use in an outbound connectivity
 * checks. No more than 'dest_len' characters (including terminating
 * NULL) is ever written to the 'dest'.
 */
static
size_t priv_gen_username (NiceAgent *agent, guint component_id,
    gchar *remote, gchar *local, uint8_t *dest, guint dest_len)
{
  guint len = 0;
  gsize remote_len = strlen (remote);
  gsize local_len = strlen (local);

  if (remote_len > 0 && local_len > 0) {
    if (agent->compatibility == NICE_COMPATIBILITY_RFC5245 &&
        dest_len >= remote_len + local_len + 1) {
      memcpy (dest, remote, remote_len);
      len += remote_len;
      memcpy (dest + len, ":", 1);
      len++;
      memcpy (dest + len, local, local_len);
      len += local_len;
    } else if ((agent->compatibility == NICE_COMPATIBILITY_WLM2009 ||
        agent->compatibility == NICE_COMPATIBILITY_OC2007R2) &&
        dest_len >= remote_len + local_len + 4 ) {
      memcpy (dest, remote, remote_len);
      len += remote_len;
      memcpy (dest + len, ":", 1);
      len++;
      memcpy (dest + len, local, local_len);
      len += local_len;
      if (len % 4 != 0) {
        memset (dest + len, 0, 4 - (len % 4));
        len += 4 - (len % 4);
      }
    } else if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE &&
        dest_len >= remote_len + local_len) {
      memcpy (dest, remote, remote_len);
      len += remote_len;
      memcpy (dest + len, local, local_len);
      len += local_len;
    } else if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
	       agent->compatibility == NICE_COMPATIBILITY_OC2007) {
      gchar component_str[10];
      guchar *local_decoded = NULL;
      guchar *remote_decoded = NULL;
      gsize local_decoded_len;
      gsize remote_decoded_len;
      gsize total_len;
      int padding;

      g_snprintf (component_str, sizeof(component_str), "%d", component_id);
      local_decoded = g_base64_decode (local, &local_decoded_len);
      remote_decoded = g_base64_decode (remote, &remote_decoded_len);

      total_len = remote_decoded_len + local_decoded_len + 3 + 2*strlen (component_str);
      padding = 4 - (total_len % 4);

      if (dest_len >= total_len + padding) {
        guchar pad_char[1] = {0};
        int i;

        memcpy (dest, remote_decoded, remote_decoded_len);
        len += remote_decoded_len;
        memcpy (dest + len, ":", 1);
        len++;
        memcpy (dest + len, component_str, strlen (component_str));
        len += strlen (component_str);

        memcpy (dest + len, ":", 1);
        len++;

        memcpy (dest + len, local_decoded, local_decoded_len);
        len += local_decoded_len;
        memcpy (dest + len, ":", 1);
        len++;
        memcpy (dest + len, component_str, strlen (component_str));;
        len += strlen (component_str);

        for (i = 0; i < padding; i++) {
          memcpy (dest + len, pad_char, 1);
          len++;
        }

      }

      g_free (local_decoded);
      g_free (remote_decoded);
    }
  }

  return len;
}

/*
 * Fills 'dest' with a username string for use in an outbound connectivity
 * checks. No more than 'dest_len' characters (including terminating
 * NULL) is ever written to the 'dest'.
 */
static
size_t priv_create_username (NiceAgent *agent, NiceStream *stream,
    guint component_id, NiceCandidate *remote, NiceCandidate *local,
    uint8_t *dest, guint dest_len, gboolean inbound)
{
  gchar *local_username = NULL;
  gchar *remote_username = NULL;


  if (remote && remote->username) {
    remote_username = remote->username;
  }

  if (local && local->username) {
    local_username = local->username;
  }

  if (stream) {
    if (remote_username == NULL) {
      remote_username = stream->remote_ufrag;
    }
    if (local_username == NULL) {
      local_username = stream->local_ufrag;
    }
  }

  if (local_username && remote_username) {
    if (inbound) {
      return priv_gen_username (agent, component_id,
          local_username, remote_username, dest, dest_len);
    } else {
      return priv_gen_username (agent, component_id,
          remote_username, local_username, dest, dest_len);
    }
  }

  return 0;
}

/*
 * Returns a password string for use in an outbound connectivity
 * check.
 */
static
size_t priv_get_password (NiceAgent *agent, NiceStream *stream,
    NiceCandidate *remote, uint8_t **password)
{
  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE)
    return 0;

  if (remote && remote->password) {
    *password = (uint8_t *)remote->password;
    return strlen (remote->password);
  }

  if (stream) {
    *password = (uint8_t *)stream->remote_password;
    return strlen (stream->remote_password);
  }

  return 0;
}

/* Implement the computation specific in RFC 5245 section 16 */

static unsigned int priv_compute_conncheck_timer (NiceAgent *agent, NiceStream *stream)
{
  GSList *i;
  guint waiting_and_in_progress = 0;
  guint n = 0;
  unsigned int rto = 0;

  for (i = stream->conncheck_list; i ; i = i->next) {
    CandidateCheckPair *p = i->data;
    if (p->state == NICE_CHECK_IN_PROGRESS ||
        p->state == NICE_CHECK_WAITING)
      waiting_and_in_progress++;
  }

  n = priv_number_of_active_check_lists (agent);
  rto = agent->timer_ta  * n * waiting_and_in_progress;

  /* We assume non-reliable streams are RTP, so we use 100 as the max */
  nice_debug ("Agent %p : timer set to %dms, "
    "waiting+in_progress=%d, nb_active=%d",
    agent, agent->reliable ? MAX (rto, 500) : MAX (rto, 100),
    waiting_and_in_progress, n);
  if (agent->reliable)
    return MAX (rto, 500);
  else
    return MAX (rto, 100);
}

/*
 * Sends a connectivity check over candidate pair 'pair'.
 *
 * @return zero on success, non-zero on error
 */
int conn_check_send (NiceAgent *agent, CandidateCheckPair *pair)
{

  /* note: following information is supplied:
   *  - username (for USERNAME attribute)
   *  - password (for MESSAGE-INTEGRITY)
   *  - priority (for PRIORITY)
   *  - ICE-CONTROLLED/ICE-CONTROLLING (for role conflicts)
   *  - USE-CANDIDATE (if sent by the controlling agent)
   */

  uint8_t uname[NICE_STREAM_MAX_UNAME];
  NiceStream *stream;
  NiceComponent *component;
  gsize uname_len;
  uint8_t *password = NULL;
  gsize password_len;
  bool controlling = agent->controlling_mode;
 /* XXX: add API to support different nomination modes: */
  bool cand_use = controlling;
  size_t buffer_len;
  unsigned int timeout;
  StunTransaction *stun;

  if (!agent_find_component (agent, pair->stream_id, pair->component_id,
          &stream, &component))
    return -1;

  uname_len = priv_create_username (agent, stream, pair->component_id,
      pair->remote, pair->local, uname, sizeof (uname), FALSE);
  password_len = priv_get_password (agent, stream, pair->remote, &password);

  if (password != NULL &&
      (agent->compatibility == NICE_COMPATIBILITY_MSN ||
       agent->compatibility == NICE_COMPATIBILITY_OC2007)) {
    password = g_base64_decode ((gchar *) password, &password_len);
  }

  if (nice_debug_is_enabled ()) {
    gchar tmpbuf1[INET6_ADDRSTRLEN];
    gchar tmpbuf2[INET6_ADDRSTRLEN];
    nice_address_to_string (&pair->local->addr, tmpbuf1);
    nice_address_to_string (&pair->remote->addr, tmpbuf2);
    nice_debug ("Agent %p : STUN-CC REQ [%s]:%u --> [%s]:%u, socket=%u, "
        "pair=%p (c-id:%u), tie=%llu, username='%.*s' (%" G_GSIZE_FORMAT "), "
        "password='%.*s' (%" G_GSIZE_FORMAT "), prio=%08x, %s.", agent,
	     tmpbuf1, nice_address_get_port (&pair->local->addr),
	     tmpbuf2, nice_address_get_port (&pair->remote->addr),
             pair->sockptr->fileno ? g_socket_get_fd(pair->sockptr->fileno) : -1,
	     pair, pair->component_id,
	     (unsigned long long)agent->tie_breaker,
        (int) uname_len, uname, uname_len,
        (int) password_len, password, password_len,
        pair->stun_priority,
        controlling ? "controlling" : "controlled");
  }

  if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent)) {
    switch (agent->nomination_mode) {
      case NICE_NOMINATION_MODE_REGULAR:
        /* We are doing regular nomination, so we set the use-candidate
         * attrib, when the controlling agent decided which valid pair to
         * resend with this flag in priv_conn_check_tick_stream()
         */
        cand_use = pair->use_candidate_on_next_check;
        nice_debug ("Agent %p : %s: set cand_use=%d "
            "(regular nomination).", agent, G_STRFUNC, cand_use);
        break;
      case NICE_NOMINATION_MODE_AGGRESSIVE:
        /* We are doing aggressive nomination, we set the use-candidate
         * attrib in every check we send, when we are the controlling
         * agent, RFC 5245, 8.1.1.2
         */
        cand_use = controlling;
        nice_debug ("Agent %p : %s: set cand_use=%d "
            "(aggressive nomination).", agent, G_STRFUNC, cand_use);
        break;
      default:
        /* Nothing to do. */
        break;
    }
  } else if (cand_use)
    pair->nominated = controlling;

  if (uname_len == 0) {
    nice_debug ("Agent %p: no credentials found, cancelling conncheck", agent);
    return -1;
  }

  stun = priv_add_stun_transaction (pair);

  buffer_len = stun_usage_ice_conncheck_create (&component->stun_agent,
      &stun->message, stun->buffer, sizeof(stun->buffer),
      uname, uname_len, password, password_len,
      cand_use, controlling, pair->stun_priority,
      agent->tie_breaker,
      pair->local->foundation,
      agent_to_ice_compatibility (agent));

  nice_debug ("Agent %p: conncheck created %zd - %p", agent, buffer_len,
      stun->message.buffer);

  if (agent->compatibility == NICE_COMPATIBILITY_MSN ||
      agent->compatibility == NICE_COMPATIBILITY_OC2007) {
    g_free (password);
  }

  if (buffer_len == 0) {
    nice_debug ("Agent %p: buffer is empty, cancelling conncheck", agent);
    priv_remove_stun_transaction (pair, stun, component);
    return -1;
  }

  if (nice_socket_is_reliable(pair->sockptr)) {
    timeout = agent->stun_reliable_timeout;
    stun_timer_start_reliable(&stun->timer, timeout);
  } else {
    timeout = priv_compute_conncheck_timer (agent, stream);
    stun_timer_start (&stun->timer, timeout, agent->stun_max_retransmissions);
  }

  stun->next_tick = g_get_monotonic_time () + timeout * 1000;

  /* TCP-ACTIVE candidate must create a new socket before sending
   * by connecting to the peer. The new socket is stored in the candidate
   * check pair, until we discover a new local peer reflexive */
  if (pair->sockptr->fileno == NULL &&
      pair->sockptr->type != NICE_SOCKET_TYPE_UDP_TURN &&
      pair->local->transport == NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE) {
    NiceStream *stream2 = NULL;
    NiceComponent *component2 = NULL;
    NiceSocket *new_socket;

    if (agent_find_component (agent, pair->stream_id, pair->component_id,
            &stream2, &component2)) {
      new_socket = nice_tcp_active_socket_connect (pair->sockptr,
          &pair->remote->addr);
      if (new_socket) {
        nice_debug ("Agent %p: add to tcp-act socket %p a new "
            "tcp connect socket %p on pair %p in s/c %d/%d",
            agent, pair->sockptr, new_socket, pair, stream->id, component->id);
        pair->sockptr = new_socket;
        _priv_set_socket_tos (agent, pair->sockptr, stream2->tos);

        nice_socket_set_writable_callback (pair->sockptr, _tcp_sock_is_writable,
            component2);

        nice_component_attach_socket (component2, new_socket);
      }
    }
  }
  /* send the conncheck */
  agent_socket_send (pair->sockptr, &pair->remote->addr,
      buffer_len, (gchar *)stun->buffer);

  if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2)
    ms_ice2_legacy_conncheck_send (&stun->message, pair->sockptr,
        &pair->remote->addr);

  return 0;
}

/*
 * Implemented the pruning steps described in ICE sect 8.1.2
 * "Updating States" (ID-19) after a pair has been nominated.
 *
 * @see conn_check_update_check_list_state_failed_components()
 */
static guint priv_prune_pending_checks (NiceAgent *agent, NiceStream *stream, NiceComponent *component)
{
  GSList *i;
  guint64 priority;
  guint in_progress = 0;
  gchar prio[NICE_CANDIDATE_PAIR_PRIORITY_MAX_SIZE];

  nice_debug ("Agent %p: Pruning pending checks for s%d/c%d",
      agent, stream->id, component->id);

  /* Called when we have at least one selected pair */
  priority = component->selected_pair.priority;
  g_assert (priority > 0);

  nice_candidate_pair_priority_to_string (priority, prio);
  nice_debug ("Agent %p : selected pair priority is %s", agent, prio);

  i = stream->conncheck_list;
  while (i) {
    CandidateCheckPair *p = i->data;
    GSList *next = i->next;

    if (p->component_id != component->id) {
      i = next;
      continue;
    }

    /* step: cancel all FROZEN and WAITING pairs for the component */
    if (p->state == NICE_CHECK_FROZEN || p->state == NICE_CHECK_WAITING) {
      nice_debug ("Agent %p : pair %p removed.", agent, p);
      candidate_check_pair_free (agent, p);
      stream->conncheck_list = g_slist_delete_link(stream->conncheck_list, i);
    }

    /* note: a SHOULD level req. in ICE 8.1.2. "Updating States" (ID-19) */
    else if (p->state == NICE_CHECK_IN_PROGRESS) {
      if (p->priority < priority) {
        priv_remove_pair_from_triggered_check_queue (agent, p);
        if (p->retransmit && p->stun_transactions) {
          p->retransmit  = FALSE;
          nice_debug ("Agent %p : pair %p will not be retransmitted.",
              agent, p);
        } else if (p->retransmit) {
          /* Pair in-progress, but stun request not yet sent */
          nice_debug ("Agent %p : pair %p removed.", agent, p);
          candidate_check_pair_free (agent, p);
          stream->conncheck_list = g_slist_delete_link(stream->conncheck_list,
              i);
        }
      } else {
        /* We must keep the higher priority pairs running because if a udp
         * packet was lost, we might end up using a bad candidate */
        nice_candidate_pair_priority_to_string (p->priority, prio);
        nice_debug ("Agent %p : pair %p kept IN_PROGRESS because priority "
            "%s is higher than priority of best nominated pair.", agent, p, prio);
        /* We may also have to enable the retransmit flag of pairs with
         * a higher priority than the first nominated pair
         */
        if (!p->retransmit && p->stun_transactions) {
          p->retransmit = TRUE;
          nice_debug ("Agent %p : pair %p will be retransmitted.", agent, p);
        }
        in_progress++;
      }
    }
    /* A triggered check on a failed pair will depend on the retransmit
     * flag, so on the relative priority of this pair and the nominated
     * pair.
     */
    else if (p->state == NICE_CHECK_FAILED)
      p->retransmit = (p->priority > priority ? TRUE : FALSE);
    i = next;
  }

  return in_progress;
}

/*
 * Schedules a triggered check after a successfully inbound 
 * connectivity check. Implements ICE sect 7.2.1.4 "Triggered Checks" (ID-19).
 * 
 * @param agent self pointer
 * @param component the check is related to
 * @param local_socket socket from which the inbound check was received
 * @param remote_cand remote candidate from which the inbound check was sent
 */
static gboolean priv_schedule_triggered_check (NiceAgent *agent, NiceStream *stream, NiceComponent *component, NiceSocket *local_socket, NiceCandidate *remote_cand)
{
  GSList *i;
  NiceCandidate *local = NULL;
  CandidateCheckPair *p;

  g_assert (remote_cand != NULL);

  nice_debug ("Agent %p : scheduling triggered check with socket=%p "
      "and remote cand=%p.", agent, local_socket, remote_cand);

  for (i = stream->conncheck_list; i ; i = i->next) {
      p = i->data;
      if (p->component_id == component->id &&
	  p->remote == remote_cand &&
          ((p->local->transport == NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE &&
              p->sockptr == local_socket) ||
              (p->local->transport != NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE &&
                  p->local->sockptr == local_socket))) {
        /* We don't check for p->sockptr because in the case of
         * tcp-active we don't want to retrigger a check on a pair that
         * was FAILED when a peer-reflexive pair was created */

        if (p->succeeded_pair != NULL) {
          g_assert_cmpint (p->state, ==, NICE_CHECK_DISCOVERED);
          p = p->succeeded_pair;
        }

	nice_debug ("Agent %p : Found a matching pair %p (%s) (%s) ...",
            agent, p, p->foundation, priv_state_to_string (p->state));
	
	switch (p->state) {
          case NICE_CHECK_WAITING:
	  case NICE_CHECK_FROZEN:
            nice_debug ("Agent %p : pair %p added for a triggered check.",
                agent, p);
            priv_add_pair_to_triggered_check_queue (agent, p);
            break;
          case NICE_CHECK_IN_PROGRESS:
            /* note: according to ICE SPEC sect 7.2.1.4 "Triggered Checks"
             * we cancel the in-progress transaction, and after the
             * retransmission timeout, we create a new connectivity check
             * for that pair.  The controlling role of this new check may
             * be different from the role of this cancelled check.
             *
             * note: the flag retransmit unset means that
             * another pair, with a higher priority is already nominated,
             * so there's no reason to recheck this pair, since it can in
             * no way replace the nominated one.
             */
            if (!nice_socket_is_reliable (p->sockptr) && p->retransmit) {
              nice_debug ("Agent %p : pair %p added for a triggered check.",
                  agent, p);
              priv_add_pair_to_triggered_check_queue (agent, p);
            }
            break;
          case NICE_CHECK_FAILED:
            if (p->retransmit) {
                nice_debug ("Agent %p : pair %p added for a triggered check.",
                    agent, p);
                priv_add_pair_to_triggered_check_queue (agent, p);
                /* If the component for this pair is in failed state, move it
                 * back to connecting, and reinitiate the timers
                 */
                if (component->state == NICE_COMPONENT_STATE_FAILED) {
                  agent_signal_component_state_change (agent, stream->id,
                      component->id, NICE_COMPONENT_STATE_CONNECTING);
                  conn_check_schedule_next (agent);
                }
            }
            break;
	  case NICE_CHECK_SUCCEEDED:
            nice_debug ("Agent %p : nothing to do for pair %p.", agent, p);
            /* note: this is a bit unsure corner-case -- let's do the
               same state update as for processing responses to our own checks */
            /* note: this update is required by the trickle test, to
             * ensure the transition ready -> connected -> ready, because
             * an incoming stun request generates a discovered peer reflexive,
             * that causes the ready -> connected transition.
             */
            conn_check_update_check_list_state_for_ready (agent, stream,
                component);
            break;
          default:
            break;
        }

	/* note: the spec says the we SHOULD retransmit in-progress
	 *       checks immediately, but we won't do that now */

	return TRUE;
      }
  }

  for (i = component->local_candidates; i ; i = i->next) {
    local = i->data;
    if (local->sockptr == local_socket)
      break;
  }

  if (i) {
    nice_debug ("Agent %p : Adding a triggered check to conn.check list (local=%p).", agent, local);
    p = priv_conn_check_add_for_candidate_pair_matched (agent, stream->id,
        component, local, remote_cand, NICE_CHECK_WAITING);
    if (p)
      priv_add_pair_to_triggered_check_queue (agent, p);
    return TRUE;
  }
  else {
    nice_debug ("Agent %p : Didn't find a matching pair for triggered check (remote-cand=%p).", agent, remote_cand);
    return FALSE;
  }
}


/*
 * Sends a reply to an successfully received STUN connectivity 
 * check request. Implements parts of the ICE spec section 7.2 (STUN
 * Server Procedures).
 *
 * @param agent context pointer
 * @param stream which stream (of the agent)
 * @param component which component (of the stream)
 * @param rcand remote candidate from which the request came, if NULL,
 *        the response is sent immediately but no other processing is done
 * @param toaddr address to which reply is sent
 * @param socket the socket over which the request came
 * @param rbuf_len length of STUN message to send
 * @param msg the STUN message to send
 * @param use_candidate whether the request had USE_CANDIDATE attribute
 * 
 * @pre (rcand == NULL || nice_address_equal(rcand->addr, toaddr) == TRUE)
 */
static void priv_reply_to_conn_check (NiceAgent *agent, NiceStream *stream,
    NiceComponent *component, NiceCandidate *lcand, NiceCandidate *rcand,
    const NiceAddress *toaddr, NiceSocket *sockptr, size_t rbuf_len,
    StunMessage *msg, gboolean use_candidate)
{
  g_assert (rcand == NULL || nice_address_equal(&rcand->addr, toaddr) == TRUE);

  if (nice_debug_is_enabled ()) {
    gchar tmpbuf[INET6_ADDRSTRLEN];
    nice_address_to_string (toaddr, tmpbuf);
    nice_debug ("Agent %p : STUN-CC RESP to '%s:%u', socket=%u, len=%u, cand=%p (c-id:%u), use-cand=%d.", agent,
	     tmpbuf,
	     nice_address_get_port (toaddr),
             sockptr->fileno ? g_socket_get_fd(sockptr->fileno) : -1,
	     (unsigned)rbuf_len,
	     rcand, component->id,
	     (int)use_candidate);
  }

  agent_socket_send (sockptr, toaddr, rbuf_len, (const gchar*)msg->buffer);
  if (agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
    ms_ice2_legacy_conncheck_send(msg, sockptr, toaddr);
  }

  /* We react to this stun request when we have the remote credentials.
   * When credentials are not yet known, this request is stored
   * in incoming_checks for later processing when returning from this
   * function.
   */
  if (rcand && stream->remote_ufrag[0]) {
    priv_schedule_triggered_check (agent, stream, component, sockptr, rcand);
    if (use_candidate)
      priv_mark_pair_nominated (agent, stream, component, lcand, rcand);
  }
}

/*
 * Stores information of an incoming STUN connectivity check
 * for later use. This is only needed when a check is received
 * before we get information about the remote candidates (via
 * SDP or other signaling means).
 *
 * @return non-zero on error, zero on success
 */
static int priv_store_pending_check (NiceAgent *agent, NiceComponent *component,
    const NiceAddress *from, NiceSocket *sockptr, uint8_t *username,
    uint16_t username_len, uint32_t priority, gboolean use_candidate)
{
  IncomingCheck *icheck;
  nice_debug ("Agent %p : Storing pending check.", agent);

  if (g_queue_get_length (&component->incoming_checks) >=
      NICE_AGENT_MAX_REMOTE_CANDIDATES) {
    nice_debug ("Agent %p : WARN: unable to store information for early incoming check.", agent);
    return -1;
  }

  icheck = g_slice_new0 (IncomingCheck);
  g_queue_push_tail (&component->incoming_checks, icheck);
  icheck->from = *from;
  icheck->local_socket = sockptr;
  icheck->priority = priority;
  icheck->use_candidate = use_candidate;
  icheck->username_len = username_len;
  icheck->username = NULL;
  if (username_len > 0)
    icheck->username = g_memdup (username, username_len);

  return 0;
}

/*
 * Adds a new pair, discovered from an incoming STUN response, to 
 * the connectivity check list.
 *
 * @return created pair, or NULL on fatal (memory allocation) errors
 */
static CandidateCheckPair *priv_add_peer_reflexive_pair (NiceAgent *agent, guint stream_id, NiceComponent *component, NiceCandidate *local_cand, CandidateCheckPair *parent_pair)
{
  CandidateCheckPair *pair = g_slice_new0 (CandidateCheckPair);
  NiceStream *stream = agent_find_stream (agent, stream_id);

  pair->stream_id = stream_id;
  pair->component_id = component->id;;
  pair->local = local_cand;
  pair->remote = parent_pair->remote;
  pair->sockptr = local_cand->sockptr;
  parent_pair->discovered_pair = pair;
  pair->succeeded_pair = parent_pair;
  nice_debug ("Agent %p : creating a new pair", agent);
  SET_PAIR_STATE (agent, pair, NICE_CHECK_DISCOVERED);
  {
      gchar tmpbuf1[INET6_ADDRSTRLEN];
      gchar tmpbuf2[INET6_ADDRSTRLEN];
      nice_address_to_string (&pair->local->addr, tmpbuf1);
      nice_address_to_string (&pair->remote->addr, tmpbuf2);
      nice_debug ("Agent %p : new pair %p : [%s]:%u --> [%s]:%u", agent, pair,
          tmpbuf1, nice_address_get_port (&pair->local->addr),
          tmpbuf2, nice_address_get_port (&pair->remote->addr));
  }
  g_snprintf (pair->foundation, NICE_CANDIDATE_PAIR_MAX_FOUNDATION, "%s:%s",
      local_cand->foundation, parent_pair->remote->foundation);

  if (agent->controlling_mode == TRUE)
    pair->priority = nice_candidate_pair_priority (pair->local->priority,
        pair->remote->priority);
  else
    pair->priority = nice_candidate_pair_priority (pair->remote->priority,
        pair->local->priority);
  pair->nominated = parent_pair->nominated;
  /* the peer-reflexive priority used in stun request is copied from
   * the parent succeeded pair. This value is not required for discovered
   * pair, that won't emit stun requests themselves, but may be used when
   * such pair becomes the selected pair, and when keepalive stun are emitted,
   * using the sockptr and stun_priority values from the succeeded pair.
   */
  pair->stun_priority = parent_pair->stun_priority;
  nice_debug ("Agent %p : added a new peer-discovered pair %p with "
      "foundation '%s' and transport %s:%s to stream %u component %u",
      agent, pair, pair->foundation,
      priv_candidate_transport_to_string (pair->local->transport),
      priv_candidate_transport_to_string (pair->remote->transport),
      stream_id, component->id);

  stream->conncheck_list = g_slist_insert_sorted (stream->conncheck_list, pair,
      (GCompareFunc)conn_check_compare);

  return pair;
}

/*
 * Recalculates priorities of all candidate pairs. This
 * is required after a conflict in ICE roles.
 */
void recalculate_pair_priorities (NiceAgent *agent)
{
  GSList *i, *j;

  for (i = agent->streams; i; i = i->next) {
    NiceStream *stream = i->data;
    for (j = stream->conncheck_list; j; j = j->next) {
      CandidateCheckPair *p = j->data;
      p->priority = agent_candidate_pair_priority (agent, p->local, p->remote);
    }
    stream->conncheck_list = g_slist_sort (stream->conncheck_list,
        (GCompareFunc)conn_check_compare);
  }
}

/*
 * Change the agent role if different from 'control'. Can be
 * initiated both by handling of incoming connectivity checks,
 * and by processing the responses to checks sent by us.
 */
static void priv_check_for_role_conflict (NiceAgent *agent, gboolean control)
{
  /* role conflict, change mode; wait for a new conn. check */
  if (control != agent->controlling_mode) {
    nice_debug ("Agent %p : Role conflict, changing agent role to \"%s\".",
        agent, control ? "controlling" : "controlled");
    agent->controlling_mode = control;
    /* the pair priorities depend on the roles, so recalculation
     * is needed */
    recalculate_pair_priorities (agent);
  }
  else 
    nice_debug ("Agent %p : Role conflict, staying with role \"%s\".",
        agent, control ? "controlling" : "controlled");
}

/*
 * Checks whether the mapped address in connectivity check response 
 * matches any of the known local candidates. If not, apply the
 * mechanism for "Discovering Peer Reflexive Candidates" ICE ID-19)
 *
 * @param agent context pointer
 * @param stream which stream (of the agent)
 * @param component which component (of the stream)
 * @param p the connectivity check pair for which we got a response
 * @param socketptr socket used to send the reply
 * @param mapped_sockaddr mapped address in the response
 *
 * @return pointer to a candidate pair, found in conncheck list or newly created
 */
static CandidateCheckPair *priv_process_response_check_for_reflexive(NiceAgent *agent, NiceStream *stream, NiceComponent *component, CandidateCheckPair *p, NiceSocket *sockptr, struct sockaddr *mapped_sockaddr, NiceCandidate *local_candidate, NiceCandidate *remote_candidate)
{
  CandidateCheckPair *new_pair = NULL;
  NiceAddress mapped;
  GSList *i;
  NiceCandidate *local_cand = NULL;

  nice_address_set_from_sockaddr (&mapped, mapped_sockaddr);

  for (i = component->local_candidates; i; i = i->next) {
    NiceCandidate *cand = i->data;

    if (nice_address_equal (&mapped, &cand->addr) &&
        local_candidate_and_socket_compatible (agent, cand, sockptr)) {
      local_cand = cand;
      break;
    }
  }

  /* The mapped address allows to look for a previously discovered
   * peer reflexive local candidate, and its related pair. This
   * new_pair will be marked 'Valid', while the pair 'p' of the
   * initial stun request will be marked 'Succeeded'
   *
   * In the case of a tcp-act/tcp-pass pair 'p', where the local
   * candidate is of type tcp-act, and its port number is zero, a
   * conncheck on this pair *always* leads to the creation of a
   * discovered peer-reflexive tcp-act local candidate.
   */
  for (i = stream->conncheck_list; i; i = i->next) {
    CandidateCheckPair *pair = i->data;
    if (local_cand == pair->local && remote_candidate == pair->remote) {
      new_pair = pair;
      break;
    }
  }

  if (new_pair) {
    /* note: when new_pair is distinct from p, it means new_pair is a
     * previously discovered peer-reflexive candidate pair, so we don't
     * set the valid flag on p in this case, because the valid flag is
     * already set on the discovered pair.
     */
    if (new_pair == p)
      p->valid = TRUE;
    SET_PAIR_STATE (agent, p, NICE_CHECK_SUCCEEDED);
    priv_remove_pair_from_triggered_check_queue (agent, p);
    priv_free_all_stun_transactions (p, component);
    nice_component_add_valid_candidate (agent, component, remote_candidate);
  }
  else {
    if (!local_cand) {
      if (!agent->force_relay) {
        /* step: find a new local candidate, see RFC 5245 7.1.3.2.1.
         * "Discovering Peer Reflexive Candidates"
         *
         * The priority equal to the value of the PRIORITY attribute
         * in the Binding request is taken from the "parent" pair p
         */
        local_cand = discovery_add_peer_reflexive_candidate (agent,
                                                             stream->id,
                                                             component->id,
                                                             p->stun_priority,
                                                            &mapped,
                                                             sockptr,
                                                             local_candidate,
                                                             remote_candidate);
        nice_debug ("Agent %p : added a new peer-reflexive local candidate %p "
            "with transport %s", agent, local_cand,
            priv_candidate_transport_to_string (local_cand->transport));
      }
    }

    /* step: add a new discovered pair (see RFC 5245 7.1.3.2.2
	       "Constructing a Valid Pair") */
    if (local_cand)
      new_pair = priv_add_peer_reflexive_pair (agent, stream->id, component,
          local_cand, p);
    /* note: this is same as "adding to VALID LIST" in the spec
       text */
    if (new_pair)
      new_pair->valid = TRUE;
    /* step: The agent sets the state of the pair that *generated* the check to
     * Succeeded, RFC 5245, 7.1.3.2.3, "Updating Pair States"
     */
    SET_PAIR_STATE (agent, p, NICE_CHECK_SUCCEEDED);
    priv_remove_pair_from_triggered_check_queue (agent, p);
    priv_free_all_stun_transactions (p, component);
  }

  if (new_pair && new_pair->valid)
    nice_component_add_valid_candidate (agent, component, remote_candidate);


  return new_pair;
}

/*
 * Tries to match STUN reply in 'buf' to an existing STUN connectivity
 * check transaction. If found, the reply is processed. Implements
 * section 7.1.2 "Processing the Response" of ICE spec (ID-19).
 *
 * @return TRUE if a matching transaction is found
 */
static gboolean priv_map_reply_to_conn_check_request (NiceAgent *agent, NiceStream *stream, NiceComponent *component, NiceSocket *sockptr, const NiceAddress *from, NiceCandidate *local_candidate, NiceCandidate *remote_candidate, StunMessage *resp)
{
  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } sockaddr;
  socklen_t socklen = sizeof (sockaddr);
  GSList *i, *j;
  guint k;
  StunUsageIceReturn res;
  StunTransactionId discovery_id;
  StunTransactionId response_id;
  stun_message_id (resp, response_id);

  for (i = stream->conncheck_list; i; i = i->next) {
    CandidateCheckPair *p = i->data;

    for (j = p->stun_transactions, k = 0; j; j = j->next, k++) {
      StunTransaction *stun = j->data;

      stun_message_id (&stun->message, discovery_id);

      if (memcmp (discovery_id, response_id, sizeof(StunTransactionId)))
	continue;

      res = stun_usage_ice_conncheck_process (resp,
	  &sockaddr.storage, &socklen,
	  agent_to_ice_compatibility (agent));
      nice_debug ("Agent %p : stun_bind_process/conncheck for %p: "
	  "%s,res=%s,stun#=%d.",
	  agent, p,
	  agent->controlling_mode ? "controlling" : "controlled",
	  priv_ice_return_to_string (res), k);

      if (res == STUN_USAGE_ICE_RETURN_SUCCESS ||
	  res == STUN_USAGE_ICE_RETURN_NO_MAPPED_ADDRESS) {
	/* case: found a matching connectivity check request */

	CandidateCheckPair *ok_pair = NULL;

	nice_debug ("Agent %p : pair %p MATCHED.", agent, p);
	priv_remove_stun_transaction (p, stun, component);

	/* step: verify that response came from the same IP address we
	 *       sent the original request to (see 7.1.2.1. "Failure
	 *       Cases") */
	if (nice_address_equal (from, &p->remote->addr) == FALSE) {
	  candidate_check_pair_fail (stream, agent, p);
	  if (nice_debug_is_enabled ()) {
	    gchar tmpbuf[INET6_ADDRSTRLEN];
	    gchar tmpbuf2[INET6_ADDRSTRLEN];
	    nice_debug ("Agent %p : pair %p FAILED"
		" (mismatch of source address).", agent, p);
	    nice_address_to_string (&p->remote->addr, tmpbuf);
	    nice_address_to_string (from, tmpbuf2);
	    nice_debug ("Agent %p : '%s:%u' != '%s:%u'", agent,
		tmpbuf, nice_address_get_port (&p->remote->addr),
		tmpbuf2, nice_address_get_port (from));
	  }
	  return TRUE;
	}

        if (remote_candidate == NULL) {
          candidate_check_pair_fail (stream, agent, p);
          if (nice_debug_is_enabled ()) {
            nice_debug ("Agent %p : pair %p FAILED "
                "(got a matching pair without a known remote candidate).", agent, p);
          }
          return TRUE;
        }

	/* note: CONNECTED but not yet READY, see docs */

	/* step: handle the possible case of a peer-reflexive
	 *       candidate where the mapped-address in response does
	 *       not match any local candidate, see 7.1.2.2.1
	 *       "Discovering Peer Reflexive Candidates" ICE ID-19) */

        if (res == STUN_USAGE_ICE_RETURN_NO_MAPPED_ADDRESS) {
          nice_debug ("Agent %p : Mapped address not found", agent);
          SET_PAIR_STATE (agent, p, NICE_CHECK_SUCCEEDED);
          p->valid = TRUE;
          nice_component_add_valid_candidate (agent, component, p->remote);
        } else
          ok_pair = priv_process_response_check_for_reflexive (agent,
              stream, component, p, sockptr, &sockaddr.addr,
              local_candidate, remote_candidate);

	/* note: The success of this check might also
	 * cause the state of other checks to change as well, ICE
	 * spec 7.1.3.2.3
	 */
	priv_conn_check_unfreeze_related (agent, stream, p);

	/* Note: this assignment helps to reduce the numbers of cases
	 * to be tested. If ok_pair and p refer to distinct pairs, it
	 * means that ok_pair is a discovered peer reflexive one,
	 * caused by the check made on pair p.  In that case, the
	 * flags to be tested are on p, but the nominated flag will be
	 * set on ok_pair. When there's no discovered pair, p and
	 * ok_pair refer to the same pair.
	 * To summarize : p is a SUCCEEDED pair, ok_pair is a
	 * DISCOVERED, VALID, and eventually NOMINATED pair. 
	 */
	if (!ok_pair)
	  ok_pair = p;

	/* step: updating nominated flag (ICE 7.1.2.2.4 "Updating the
	   Nominated Flag" (ID-19) */
	if (NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent)) {
	  nice_debug ("Agent %p : Updating nominated flag (%s): "
	      "ok_pair=%p (%d/%d) p=%p (%d/%d) (ucnc/mnora)",
	      agent, p->local->transport == NICE_CANDIDATE_TRANSPORT_UDP ?
		"UDP" : "TCP",
	      ok_pair, ok_pair->use_candidate_on_next_check,
	      ok_pair->mark_nominated_on_response_arrival,
	      p, p->use_candidate_on_next_check,
	      p->mark_nominated_on_response_arrival);

	  if (agent->controlling_mode) {
	    switch (agent->nomination_mode) {
	      case NICE_NOMINATION_MODE_REGULAR:
		if (p->use_candidate_on_next_check) {
		  nice_debug ("Agent %p : marking pair %p (%s) as nominated "
		      "(regular nomination, controlling, "
		      "use_cand_on_next_check=1).",
		      agent, ok_pair, ok_pair->foundation);
		  ok_pair->nominated = TRUE;
		}
		break;
	      case NICE_NOMINATION_MODE_AGGRESSIVE:
		if (!p->nominated) {
		  nice_debug ("Agent %p : marking pair %p (%s) as nominated "
		      "(aggressive nomination, controlling).",
		      agent, ok_pair, ok_pair->foundation);
		  ok_pair->nominated = TRUE;
		}
		break;
	      default:
		/* Nothing to do */
		break;
	    }
	  } else {
	    if (p->mark_nominated_on_response_arrival) {
	      nice_debug ("Agent %p : marking pair %p (%s) as nominated "
		  "(%s nomination, controlled, mark_on_response=1).",
		  agent, ok_pair, ok_pair->foundation,
		  agent->nomination_mode == NICE_NOMINATION_MODE_AGGRESSIVE ?
		    "aggressive" : "regular");
	      ok_pair->nominated = TRUE;
	    }
	  }
	}

	if (ok_pair->nominated == TRUE) {
          conn_check_update_selected_pair (agent, component, ok_pair);
	  priv_print_conn_check_lists (agent, G_STRFUNC,
	      ", got a nominated pair");

	  /* Do not step down to CONNECTED if we're already at state READY*/
	  if (component->state != NICE_COMPONENT_STATE_READY)
	    /* step: notify the client of a new component state (must be done
	     *       before the possible check list state update step */
	    agent_signal_component_state_change (agent,
		stream->id, component->id, NICE_COMPONENT_STATE_CONNECTED);
	}

	/* step: update pair states (ICE 7.1.2.2.3 "Updating pair
	   states" and 8.1.2 "Updating States", ID-19) */
	conn_check_update_check_list_state_for_ready (agent, stream, component);
      } else if (res == STUN_USAGE_ICE_RETURN_ROLE_CONFLICT) {
        uint64_t tie;
        gboolean controlled_mode;

	/* case: role conflict error, need to restart with new role */
	nice_debug ("Agent %p : Role conflict with pair %p, restarting",
            agent, p);

	/* note: this res value indicates that the role of the peer
	 * agent has not changed after the tie-breaker comparison, so
	 * this is our role that must change. see ICE sect. 7.1.3.1
	 * "Failure Cases". Our role might already have changed due to
	 * an earlier incoming request, but if not, change role now.
	 *
	 * Sect. 7.1.3.1 is not clear on this point, but we choose to
	 * put the candidate pair in the triggered check list even
	 * when the agent did not switch its role. The reason for this
	 * interpretation is that the reception of the stun reply, even
	 * an error reply, is a good sign that this pair will be
	 * valid, if we retry the check after the role of both peers
	 * has been fixed.
	 */
        controlled_mode = (stun_message_find64 (&stun->message,
            STUN_ATTRIBUTE_ICE_CONTROLLED, &tie) ==
            STUN_MESSAGE_RETURN_SUCCESS);

        priv_check_for_role_conflict (agent, controlled_mode);
	priv_remove_stun_transaction (p, stun, component);
        priv_add_pair_to_triggered_check_queue (agent, p);
      } else {
	/* case: STUN error, the check STUN context was freed */
	candidate_check_pair_fail (stream, agent, p);
      }
      return TRUE;
    }
  }

  return FALSE;
}

/*
 * Tries to match STUN reply in 'buf' to an existing STUN discovery
 * transaction. If found, a reply is sent.
 *
 * @return TRUE if a matching transaction is found
 */
static gboolean priv_map_reply_to_discovery_request (NiceAgent *agent, StunMessage *resp)
{
  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } sockaddr;
  socklen_t socklen = sizeof (sockaddr);

  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } alternate;
  socklen_t alternatelen = sizeof (sockaddr);

  GSList *i;
  StunUsageBindReturn res;
  gboolean trans_found = FALSE;
  StunTransactionId discovery_id;
  StunTransactionId response_id;
  stun_message_id (resp, response_id);

  for (i = agent->discovery_list; i && trans_found != TRUE; i = i->next) {
    CandidateDiscovery *d = i->data;

    if (d->type == NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE &&
        d->stun_message.buffer) {
      stun_message_id (&d->stun_message, discovery_id);

      if (memcmp (discovery_id, response_id, sizeof(StunTransactionId)) == 0) {
        res = stun_usage_bind_process (resp, &sockaddr.addr,
            &socklen, &alternate.addr, &alternatelen);
        nice_debug ("Agent %p : stun_bind_process/disc for %p res %d.",
            agent, d, (int)res);

        if (res == STUN_USAGE_BIND_RETURN_ALTERNATE_SERVER) {
          /* handle alternate server */
          NiceAddress niceaddr;
          nice_address_set_from_sockaddr (&niceaddr, &alternate.addr);
          d->server = niceaddr;

          d->pending = FALSE;
          agent->discovery_unsched_items++;
        } else if (res == STUN_USAGE_BIND_RETURN_SUCCESS) {
          /* case: successful binding discovery, create a new local candidate */

          if (!agent->force_relay) {
            NiceAddress niceaddr;

            nice_address_set_from_sockaddr (&niceaddr, &sockaddr.addr);
            discovery_add_server_reflexive_candidate (
                agent,
                d->stream_id,
                d->component_id,
                &niceaddr,
                NICE_CANDIDATE_TRANSPORT_UDP,
                d->nicesock,
                FALSE);
            if (agent->use_ice_tcp)
              discovery_discover_tcp_server_reflexive_candidates (
                  agent,
                  d->stream_id,
                  d->component_id,
                  &niceaddr,
                  d->nicesock);
          }
          d->stun_message.buffer = NULL;
          d->stun_message.buffer_len = 0;
          d->done = TRUE;
          trans_found = TRUE;
        } else if (res == STUN_USAGE_BIND_RETURN_ERROR) {
          /* case: STUN error, the check STUN context was freed */
          d->stun_message.buffer = NULL;
          d->stun_message.buffer_len = 0;
          d->done = TRUE;
          trans_found = TRUE;
        }
      }
    }
  }

  return trans_found;
}

static guint
priv_calc_turn_timeout (guint lifetime)
{
  if (lifetime > 120)
    return lifetime - 60;
  else
    return lifetime / 2;
}

static CandidateRefresh *
priv_add_new_turn_refresh (NiceAgent *agent, CandidateDiscovery *cdisco,
    NiceCandidate *relay_cand, guint lifetime)
{
  CandidateRefresh *cand;

  cand = g_slice_new0 (CandidateRefresh);
  agent->refresh_list = g_slist_append (agent->refresh_list, cand);

  cand->candidate = relay_cand;
  cand->nicesock = cdisco->nicesock;
  cand->server = cdisco->server;
  cand->stream_id = cdisco->stream_id;
  cand->component_id = cdisco->component_id;
  memcpy (&cand->stun_agent, &cdisco->stun_agent, sizeof(StunAgent));

  /* Use previous stun response for authentication credentials */
  if (cdisco->stun_resp_msg.buffer != NULL) {
    memcpy(cand->stun_resp_buffer, cdisco->stun_resp_buffer,
        sizeof(cand->stun_resp_buffer));
    memcpy(&cand->stun_resp_msg, &cdisco->stun_resp_msg, sizeof(StunMessage));
    cand->stun_resp_msg.buffer = cand->stun_resp_buffer;
    cand->stun_resp_msg.agent = NULL;
    cand->stun_resp_msg.key = NULL;
  }

  nice_debug ("Agent %p : Adding new refresh candidate %p with timeout %d",
      agent, cand, priv_calc_turn_timeout (lifetime));
  /* step: also start the refresh timer */
  /* refresh should be sent 1 minute before it expires */
  agent_timeout_add_seconds_with_context (agent, &cand->timer_source,
      "Candidate TURN refresh",
      priv_calc_turn_timeout (lifetime),
      priv_turn_allocate_refresh_tick_agent_locked, cand);

  nice_debug ("timer source is : %p", cand->timer_source);

  return cand;
}

static void priv_handle_turn_alternate_server (NiceAgent *agent,
    CandidateDiscovery *disco, NiceAddress server, NiceAddress alternate)
{
  /* We need to cancel and reset all candidate discovery turn for the same
     stream and type if there is an alternate server. Otherwise, we might end up
     with two relay components on different servers, creating candidates with
     unique foundations that only contain one component.
  */
  GSList *i;

  for (i = agent->discovery_list; i; i = i->next) {
    CandidateDiscovery *d = i->data;

    if (!d->done &&
        d->type == disco->type &&
        d->stream_id == disco->stream_id &&
        d->turn->type == disco->turn->type &&
        nice_address_equal (&d->server, &server)) {
      gchar ip[INET6_ADDRSTRLEN];
      // Cancel the pending request to avoid a race condition with another
      // component responding with another altenrate-server
      d->stun_message.buffer = NULL;
      d->stun_message.buffer_len = 0;

      nice_address_to_string (&server, ip);
      nice_debug ("Agent %p : Cancelling and setting alternate server %s for "
          "CandidateDiscovery %p", agent, ip, d);
      d->server = alternate;
      d->turn->server = alternate;
      d->pending = FALSE;
      agent->discovery_unsched_items++;
    }
  }
}

/*
 * Tries to match STUN reply in 'buf' to an existing STUN discovery
 * transaction. If found, a reply is sent.
 * 
 * @return TRUE if a matching transaction is found
 */
static gboolean priv_map_reply_to_relay_request (NiceAgent *agent, StunMessage *resp)
{
  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } sockaddr;
  socklen_t socklen = sizeof (sockaddr);

  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } alternate;
  socklen_t alternatelen = sizeof (alternate);

  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } relayaddr;
  socklen_t relayaddrlen = sizeof (relayaddr);

  uint32_t lifetime;
  uint32_t bandwidth;
  GSList *i;
  StunUsageTurnReturn res;
  gboolean trans_found = FALSE;
  StunTransactionId discovery_id;
  StunTransactionId response_id;
  stun_message_id (resp, response_id);

  for (i = agent->discovery_list; i && trans_found != TRUE; i = i->next) {
    CandidateDiscovery *d = i->data;

    if (d->type == NICE_CANDIDATE_TYPE_RELAYED &&
        d->stun_message.buffer) {
      stun_message_id (&d->stun_message, discovery_id);

      if (memcmp (discovery_id, response_id, sizeof(StunTransactionId)) == 0) {
        res = stun_usage_turn_process (resp,
            &relayaddr.storage, &relayaddrlen,
            &sockaddr.storage, &socklen,
            &alternate.storage, &alternatelen,
            &bandwidth, &lifetime, agent_to_turn_compatibility (agent));
        nice_debug ("Agent %p : stun_turn_process/disc for %p res %d.",
            agent, d, (int)res);

        if (res == STUN_USAGE_TURN_RETURN_ALTERNATE_SERVER) {
          NiceAddress addr;

          /* handle alternate server */
          nice_address_set_from_sockaddr (&addr, &alternate.addr);
          priv_handle_turn_alternate_server (agent, d, d->server, addr);
        } else if (res == STUN_USAGE_TURN_RETURN_RELAY_SUCCESS ||
                   res == STUN_USAGE_TURN_RETURN_MAPPED_SUCCESS) {
          /* case: successful allocate, create a new local candidate */
          NiceAddress niceaddr;
          NiceCandidate *relay_cand;

          nice_address_set_from_sockaddr (&niceaddr, &relayaddr.addr);

          if (res == STUN_USAGE_TURN_RETURN_MAPPED_SUCCESS) {
            NiceAddress mappedniceaddr;

            /* We also received our mapped address */
            nice_address_set_from_sockaddr (&mappedniceaddr, &sockaddr.addr);

            /* TCP or TLS TURNS means the server-reflexive address was
             * on a TCP connection, which cannot be used for server-reflexive
             * discovery of candidates.
             */
            if (d->turn->type == NICE_RELAY_TYPE_TURN_UDP &&
                !agent->force_relay) {
              discovery_add_server_reflexive_candidate (
                  agent,
                  d->stream_id,
                  d->component_id,
                  &mappedniceaddr,
                  NICE_CANDIDATE_TRANSPORT_UDP,
                  d->nicesock,
                  FALSE);
            }
            if (agent->use_ice_tcp) {
              if ((agent->compatibility == NICE_COMPATIBILITY_OC2007 ||
                   agent->compatibility == NICE_COMPATIBILITY_OC2007R2) &&
                  !nice_address_equal_no_port (&niceaddr, &d->turn->server)) {
                  nice_debug("TURN port got allocated on an alternate server, "
                             "ignoring bogus srflx address");
              } else {
                discovery_discover_tcp_server_reflexive_candidates (
                    agent,
                    d->stream_id,
                    d->component_id,
                    &mappedniceaddr,
                    d->nicesock);
              }
            }
          }

          if (nice_socket_is_reliable (d->nicesock)) {
            relay_cand = discovery_add_relay_candidate (
                agent,
                d->stream_id,
                d->component_id,
                &niceaddr,
                NICE_CANDIDATE_TRANSPORT_TCP_ACTIVE,
                d->nicesock,
                d->turn);

            if (relay_cand) {
              if (agent->compatibility == NICE_COMPATIBILITY_OC2007 ||
                  agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
                nice_udp_turn_socket_set_ms_realm(relay_cand->sockptr,
                    &d->stun_message);
                nice_udp_turn_socket_set_ms_connection_id(relay_cand->sockptr,
                    resp);
              } else {
                priv_add_new_turn_refresh (agent, d, relay_cand, lifetime);
              }
            }

            relay_cand = discovery_add_relay_candidate (
                agent,
                d->stream_id,
                d->component_id,
                &niceaddr,
                NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE,
                d->nicesock,
                d->turn);
          } else {
            relay_cand = discovery_add_relay_candidate (
                agent,
                d->stream_id,
                d->component_id,
                &niceaddr,
                NICE_CANDIDATE_TRANSPORT_UDP,
                d->nicesock,
                d->turn);
          }

          if (relay_cand) {
	    if (d->stun_resp_msg.buffer)
	      nice_udp_turn_socket_cache_realm_nonce (relay_cand->sockptr,
                  &d->stun_resp_msg);
            if (agent->compatibility == NICE_COMPATIBILITY_OC2007 ||
                agent->compatibility == NICE_COMPATIBILITY_OC2007R2) {
              /* These data are needed on TURN socket when sending requests,
               * but never reach nice_turn_socket_parse_recv() where it could
               * be read directly, as the socket does not exist when allocate
               * response arrives to _nice_agent_recv(). We must set them right
               * after socket gets created in discovery_add_relay_candidate(),
               * so we are doing it here. */
              nice_udp_turn_socket_set_ms_realm(relay_cand->sockptr,
                  &d->stun_message);
              nice_udp_turn_socket_set_ms_connection_id(relay_cand->sockptr,
                  resp);
            } else {
              priv_add_new_turn_refresh (agent, d, relay_cand, lifetime);
            }

            /* In case a new candidate has been added */
            conn_check_schedule_next (agent);
          }

          d->stun_message.buffer = NULL;
          d->stun_message.buffer_len = 0;
          d->done = TRUE;
          trans_found = TRUE;
        } else if (res == STUN_USAGE_TURN_RETURN_ERROR) {
          int code = -1;
          uint8_t *sent_realm = NULL;
          uint8_t *recv_realm = NULL;
          uint16_t sent_realm_len = 0;
          uint16_t recv_realm_len = 0;

          sent_realm = (uint8_t *) stun_message_find (&d->stun_message,
              STUN_ATTRIBUTE_REALM, &sent_realm_len);
          recv_realm = (uint8_t *) stun_message_find (resp,
              STUN_ATTRIBUTE_REALM, &recv_realm_len);

          if ((agent->compatibility == NICE_COMPATIBILITY_OC2007  ||
              agent->compatibility == NICE_COMPATIBILITY_OC2007R2) &&
              alternatelen != sizeof(alternate)) {
            NiceAddress addr;

            nice_address_set_from_sockaddr (&addr, &alternate.addr);

            if (!nice_address_equal (&addr, &d->server)) {
              priv_handle_turn_alternate_server (agent, d, d->server, addr);
            }
          }
          /* check for unauthorized error response */
          if ((agent->compatibility == NICE_COMPATIBILITY_RFC5245 ||
               agent->compatibility == NICE_COMPATIBILITY_OC2007  ||
               agent->compatibility == NICE_COMPATIBILITY_OC2007R2) &&
              stun_message_get_class (resp) == STUN_ERROR &&
              stun_message_find_error (resp, &code) ==
              STUN_MESSAGE_RETURN_SUCCESS &&
              recv_realm != NULL && recv_realm_len > 0) {

            if (code == STUN_ERROR_STALE_NONCE ||
                (code == STUN_ERROR_UNAUTHORIZED &&
                    !(recv_realm_len == sent_realm_len &&
                        sent_realm != NULL &&
                        memcmp (sent_realm, recv_realm, sent_realm_len) == 0))) {
              d->stun_resp_msg = *resp;
              memcpy (d->stun_resp_buffer, resp->buffer,
                  stun_message_length (resp));
              d->stun_resp_msg.buffer = d->stun_resp_buffer;
              d->stun_resp_msg.buffer_len = sizeof(d->stun_resp_buffer);
              d->pending = FALSE;
              agent->discovery_unsched_items++;
            } else {
              /* case: a real unauthorized error */
              d->stun_message.buffer = NULL;
              d->stun_message.buffer_len = 0;
              d->done = TRUE;
            }
          } else {
            /* case: STUN error, the check STUN context was freed */
            d->stun_message.buffer = NULL;
            d->stun_message.buffer_len = 0;
            d->done = TRUE;
          }
          trans_found = TRUE;
        }
      }
    }
  }

  return trans_found;
}


/*
 * Tries to match STUN reply in 'buf' to an existing STUN discovery
 * transaction. If found, a reply is sent.
 * 
 * @return TRUE if a matching transaction is found
 */
static gboolean priv_map_reply_to_relay_refresh (NiceAgent *agent, StunMessage *resp)
{
  uint32_t lifetime;
  GSList *i;
  StunUsageTurnReturn res;
  gboolean trans_found = FALSE;
  StunTransactionId refresh_id;
  StunTransactionId response_id;
  stun_message_id (resp, response_id);

  for (i = agent->refresh_list; i && trans_found != TRUE; i = i->next) {
    CandidateRefresh *cand = i->data;

    if (!cand->disposing && cand->stun_message.buffer) {
      stun_message_id (&cand->stun_message, refresh_id);

      if (memcmp (refresh_id, response_id, sizeof(StunTransactionId)) == 0) {
        res = stun_usage_turn_refresh_process (resp,
            &lifetime, agent_to_turn_compatibility (agent));
        nice_debug ("Agent %p : stun_turn_refresh_process for %p res %d with lifetime %u.",
            agent, cand, (int)res, lifetime);
        if (res == STUN_USAGE_TURN_RETURN_RELAY_SUCCESS) {
          /* refresh should be sent 1 minute before it expires */
          agent_timeout_add_seconds_with_context (agent,
              &cand->timer_source,
              "Candidate TURN refresh", priv_calc_turn_timeout (lifetime),
              priv_turn_allocate_refresh_tick_agent_locked, cand);

          g_source_destroy (cand->tick_source);
          g_source_unref (cand->tick_source);
          cand->tick_source = NULL;
        } else if (res == STUN_USAGE_TURN_RETURN_ERROR) {
          int code = -1;
          uint8_t *sent_realm = NULL;
          uint8_t *recv_realm = NULL;
          uint16_t sent_realm_len = 0;
          uint16_t recv_realm_len = 0;

          sent_realm = (uint8_t *) stun_message_find (&cand->stun_message,
              STUN_ATTRIBUTE_REALM, &sent_realm_len);
          recv_realm = (uint8_t *) stun_message_find (resp,
              STUN_ATTRIBUTE_REALM, &recv_realm_len);

          /* check for unauthorized error response */
          if (agent->compatibility == NICE_COMPATIBILITY_RFC5245 &&
              stun_message_get_class (resp) == STUN_ERROR &&
              stun_message_find_error (resp, &code) ==
              STUN_MESSAGE_RETURN_SUCCESS &&
              recv_realm != NULL && recv_realm_len > 0) {

            if (code == STUN_ERROR_STALE_NONCE ||
                (code == STUN_ERROR_UNAUTHORIZED &&
                    !(recv_realm_len == sent_realm_len &&
                        sent_realm != NULL &&
                        memcmp (sent_realm, recv_realm, sent_realm_len) == 0))) {
              cand->stun_resp_msg = *resp;
              memcpy (cand->stun_resp_buffer, resp->buffer,
                  stun_message_length (resp));
              cand->stun_resp_msg.buffer = cand->stun_resp_buffer;
              cand->stun_resp_msg.buffer_len = sizeof(cand->stun_resp_buffer);
              priv_turn_allocate_refresh_tick_unlocked (agent, cand);
            } else {
              /* case: a real unauthorized error */
              refresh_free (agent, cand);
            }
          } else {
            /* case: STUN error, the check STUN context was freed */
            refresh_free (agent, cand);
          }
          trans_found = TRUE;
        }
      }
    }
  }

  return trans_found;
}

static gboolean priv_map_reply_to_relay_remove (NiceAgent *agent,
    StunMessage *resp)
{
  StunTransactionId response_id;
  GSList *i;

  stun_message_id (resp, response_id);

  for (i = agent->refresh_list; i; i = i->next) {
    CandidateRefresh *cand = i->data;
    StunTransactionId request_id;
    StunUsageTurnReturn res;
    uint32_t lifetime;

    if (!cand->disposing || !cand->stun_message.buffer) {
      continue;
    }

    stun_message_id (&cand->stun_message, request_id);

    if (memcmp (request_id, response_id, sizeof(StunTransactionId)) == 0) {
      res = stun_usage_turn_refresh_process (resp, &lifetime,
          agent_to_turn_compatibility (agent));

      nice_debug ("Agent %p : priv_map_reply_to_relay_remove for %p res %d "
          "with lifetime %u.", agent, cand, res, lifetime);

      if (res != STUN_USAGE_TURN_RETURN_INVALID) {
        refresh_free (agent, cand);
        return TRUE;
      }
    }
  }

  return FALSE;
}

static gboolean priv_map_reply_to_keepalive_conncheck (NiceAgent *agent,
    NiceComponent *component, StunMessage *resp)
{
  StunTransactionId conncheck_id;
  StunTransactionId response_id;
  stun_message_id (resp, response_id);

  if (component->selected_pair.keepalive.stun_message.buffer) {
      stun_message_id (&component->selected_pair.keepalive.stun_message,
          conncheck_id);
      if (memcmp (conncheck_id, response_id, sizeof(StunTransactionId)) == 0) {
        nice_debug ("Agent %p : Keepalive for selected pair received.",
            agent);
        if (component->selected_pair.keepalive.tick_source) {
          g_source_destroy (component->selected_pair.keepalive.tick_source);
          g_source_unref (component->selected_pair.keepalive.tick_source);
          component->selected_pair.keepalive.tick_source = NULL;
        }
        component->selected_pair.keepalive.stun_message.buffer = NULL;
        return TRUE;
      }
  }

  return FALSE;
}


typedef struct {
  NiceAgent *agent;
  NiceStream *stream;
  NiceComponent *component;
  uint8_t *password;
} conncheck_validater_data;

static bool conncheck_stun_validater (StunAgent *agent,
    StunMessage *message, uint8_t *username, uint16_t username_len,
    uint8_t **password, size_t *password_len, void *user_data)
{
  conncheck_validater_data *data = (conncheck_validater_data*) user_data;
  GSList *i;
  gchar *ufrag = NULL;
  gsize ufrag_len;

  gboolean msn_msoc_nice_compatibility =
      data->agent->compatibility == NICE_COMPATIBILITY_MSN ||
      data->agent->compatibility == NICE_COMPATIBILITY_OC2007;

  if (data->agent->compatibility == NICE_COMPATIBILITY_OC2007 &&
      stun_message_get_class (message) == STUN_RESPONSE)
    i = data->component->remote_candidates;
  else
    i = data->component->local_candidates;

  for (; i; i = i->next) {
    NiceCandidate *cand = i->data;

    ufrag = NULL;
    if (cand->username)
      ufrag = cand->username;
    else
      ufrag = data->stream->local_ufrag;
    ufrag_len = ufrag? strlen (ufrag) : 0;

    if (ufrag && msn_msoc_nice_compatibility)
      ufrag = (gchar *)g_base64_decode (ufrag, &ufrag_len);

    if (ufrag == NULL)
      continue;

    stun_debug ("Comparing username/ufrag of len %d and %" G_GSIZE_FORMAT ", equal=%d",
        username_len, ufrag_len, username_len >= ufrag_len ?
        memcmp (username, ufrag, ufrag_len) : 0);
    stun_debug_bytes ("  username: ", username, username_len);
    stun_debug_bytes ("  ufrag:    ", ufrag, ufrag_len);
    if (ufrag_len > 0 && username_len >= ufrag_len &&
        memcmp (username, ufrag, ufrag_len) == 0) {
      gchar *pass = NULL;

      if (cand->password)
        pass = cand->password;
      else if (data->stream && data->stream->local_password[0])
        pass = data->stream->local_password;

      if (pass) {
        *password = (uint8_t *) pass;
        *password_len = strlen (pass);

        if (msn_msoc_nice_compatibility) {
          gsize pass_len;

          data->password = g_base64_decode (pass, &pass_len);
          *password = data->password;
          *password_len = pass_len;
        }
      }

      if (msn_msoc_nice_compatibility)
        g_free (ufrag);

      stun_debug ("Found valid username, returning password: '%s'", *password);
      return TRUE;
    }

    if (msn_msoc_nice_compatibility)
      g_free (ufrag);
  }

  return FALSE;
}

/*
 * handle RENOMINATION stun attribute
 * @return TRUE if nomination changed. FALSE otherwise
 */
static gboolean conn_check_handle_renomination (NiceAgent *agent, NiceStream *stream,
    NiceComponent *component, StunMessage *req,
    NiceCandidate *remote_candidate, NiceCandidate *local_candidate)
{
  GSList *lst;
  if (!agent->controlling_mode && NICE_AGENT_IS_COMPATIBLE_WITH_RFC5245_OR_OC2007R2 (agent) &&
      agent->support_renomination && remote_candidate && local_candidate)
  {
    uint32_t nom_value = 0;
    uint16_t nom_len = 0;
    const void *value = stun_message_find (req, STUN_ATTRIBUTE_NOMINATION, &nom_len);
    if (nom_len == 0) {
      return FALSE;
    }
    if (nom_len == 4) {
      memcpy (&nom_value, value, 4);
      nom_value = ntohl (nom_value);
    } else {
      nice_debug ("Agent %p : received NOMINATION attr with incorrect octet length %u, expected 4 bytes",
          agent, nom_len);
      return FALSE;
    }

    if (nice_debug_is_enabled ()) {
      gchar remote_str[INET6_ADDRSTRLEN];
      nice_address_to_string(&remote_candidate->addr, remote_str);
      nice_debug ("Agent %p : received NOMINATION attr for remote candidate [%s]:%u, value is %u",
          agent, remote_str, nice_address_get_port (&remote_candidate->addr), nom_value);
    }

    /*
     * If another pair is SELECTED, change this pair's priority to be greater than
     * selected pair's priority so this pair gets SELECTED!
     */
    if (component->selected_pair.priority &&
        component->selected_pair.remote && component->selected_pair.remote != remote_candidate &&
        component->selected_pair.local && component->selected_pair.local != local_candidate) {
      for (lst = stream->conncheck_list; lst; lst = lst->next) {
        CandidateCheckPair *pair = lst->data;
        if (pair->local == local_candidate && pair->remote == remote_candidate) {
          if (pair->valid) {
            pair->priority = component->selected_pair.priority + 1;
          }
          break;
        }
      }
    }
    priv_mark_pair_nominated (agent, stream, component, local_candidate, remote_candidate);
    return TRUE;
  }
  return FALSE;
}

/*
 * Processing an incoming STUN message.
 *
 * @param agent self pointer
 * @param stream stream the packet is related to
 * @param component component the packet is related to
 * @param nicesock socket from which the packet was received
 * @param from address of the sender
 * @param buf message contents
 * @param buf message length
 *
 * @pre contents of 'buf' is a STUN message
 *
 * @return XXX (what FALSE means exactly?)
 */
gboolean conn_check_handle_inbound_stun (NiceAgent *agent, NiceStream *stream,
    NiceComponent *component, NiceSocket *nicesock, const NiceAddress *from,
    gchar *buf, guint len)
{
  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } sockaddr;
  uint8_t rbuf[MAX_STUN_DATAGRAM_PAYLOAD];
  ssize_t res;
  size_t rbuf_len = sizeof (rbuf);
  bool control = agent->controlling_mode;
  uint8_t uname[NICE_STREAM_MAX_UNAME];
  guint uname_len;
  uint8_t *username;
  uint16_t username_len;
  StunMessage req;
  StunMessage msg;
  StunValidationStatus valid;
  conncheck_validater_data validater_data = {agent, stream, component, NULL};
  GSList *i, *j;
  NiceCandidate *remote_candidate = NULL;
  NiceCandidate *remote_candidate2 = NULL;
  NiceCandidate *local_candidate = NULL;
  gboolean discovery_msg = FALSE;

  nice_address_copy_to_sockaddr (from, &sockaddr.addr);

  /* note: contents of 'buf' already validated, so it is
   *       a valid and fully received STUN message */

  if (nice_debug_is_enabled ()) {
    gchar tmpbuf[INET6_ADDRSTRLEN];
    nice_address_to_string (from, tmpbuf);
    nice_debug ("Agent %p: inbound STUN packet for %u/%u (stream/component) from [%s]:%u (%u octets) :",
        agent, stream->id, component->id, tmpbuf, nice_address_get_port (from), len);
  }

  /* note: ICE  7.2. "STUN Server Procedures" (ID-19) */

  valid = stun_agent_validate (&component->stun_agent, &req,
      (uint8_t *) buf, len, conncheck_stun_validater, &validater_data);

  /* Check for discovery candidates stun agents */
  if (valid == STUN_VALIDATION_BAD_REQUEST ||
      valid == STUN_VALIDATION_UNMATCHED_RESPONSE) {
    for (i = agent->discovery_list; i; i = i->next) {
      CandidateDiscovery *d = i->data;
      if (d->stream_id == stream->id && d->component_id == component->id &&
          d->nicesock == nicesock) {
        valid = stun_agent_validate (&d->stun_agent, &req,
            (uint8_t *) buf, len, conncheck_stun_validater, &validater_data);

        if (valid == STUN_VALIDATION_UNMATCHED_RESPONSE)
          continue;

        discovery_msg = TRUE;
        break;
      }
    }
  }
  /* Check for relay refresh stun agents */
  if (valid == STUN_VALIDATION_BAD_REQUEST ||
      valid == STUN_VALIDATION_UNMATCHED_RESPONSE) {
    for (i = agent->refresh_list; i; i = i->next) {
      CandidateRefresh *r = i->data;

      nice_debug_verbose ("Comparing r.sid=%u to sid=%u, r.cid=%u to cid=%u and %p and %p to %p",
          r->stream_id, stream->id, r->component_id, component->id, r->nicesock,
          r->candidate->sockptr, nicesock);

      if (r->stream_id == stream->id && r->component_id == component->id &&
          (r->nicesock == nicesock || r->candidate->sockptr == nicesock)) {
        valid = stun_agent_validate (&r->stun_agent, &req,
            (uint8_t *) buf, len, conncheck_stun_validater, &validater_data);
        nice_debug ("Validating gave %d", valid);
        if (valid == STUN_VALIDATION_UNMATCHED_RESPONSE)
          continue;
        discovery_msg = TRUE;
        break;
      }
    }
  }

  g_free (validater_data.password);

  if (valid == STUN_VALIDATION_NOT_STUN ||
      valid == STUN_VALIDATION_INCOMPLETE_STUN ||
      valid == STUN_VALIDATION_BAD_REQUEST)
  {
    nice_debug ("Agent %p : Incorrectly multiplexed STUN message ignored.",
        agent);
    return FALSE;
  }

  if (valid == STUN_VALIDATION_UNKNOWN_REQUEST_ATTRIBUTE) {
    nice_debug ("Agent %p : Unknown mandatory attributes in message.", agent);

    if (agent->compatibility != NICE_COMPATIBILITY_MSN &&
        agent->compatibility != NICE_COMPATIBILITY_OC2007) {
      rbuf_len = stun_agent_build_unknown_attributes_error (&component->stun_agent,
          &msg, rbuf, rbuf_len, &req);
      if (rbuf_len != 0)
        agent_socket_send (nicesock, from, rbuf_len, (const gchar*)rbuf);
    }
    return TRUE;
  }

  if (valid == STUN_VALIDATION_UNAUTHORIZED) {
    nice_debug ("Agent %p : Integrity check failed.", agent);

    if (stun_agent_init_error (&component->stun_agent, &msg, rbuf, rbuf_len,
            &req, STUN_ERROR_UNAUTHORIZED)) {
      rbuf_len = stun_agent_finish_message (&component->stun_agent, &msg, NULL, 0);
      if (rbuf_len > 0 && agent->compatibility != NICE_COMPATIBILITY_MSN &&
          agent->compatibility != NICE_COMPATIBILITY_OC2007)
        agent_socket_send (nicesock, from, rbuf_len, (const gchar*)rbuf);
    }
    return TRUE;
  }
  if (valid == STUN_VALIDATION_UNAUTHORIZED_BAD_REQUEST) {
    nice_debug ("Agent %p : Integrity check failed - bad request.", agent);
    if (stun_agent_init_error (&component->stun_agent, &msg, rbuf, rbuf_len,
            &req, STUN_ERROR_BAD_REQUEST)) {
      rbuf_len = stun_agent_finish_message (&component->stun_agent, &msg, NULL, 0);
      if (rbuf_len > 0 && agent->compatibility != NICE_COMPATIBILITY_MSN &&
	  agent->compatibility != NICE_COMPATIBILITY_OC2007)
        agent_socket_send (nicesock, from, rbuf_len, (const gchar*)rbuf);
    }
    return TRUE;
  }

  username = (uint8_t *) stun_message_find (&req, STUN_ATTRIBUTE_USERNAME,
					    &username_len);

  for (i = component->local_candidates; i; i = i->next) {
    NiceCandidate *cand = i->data;
    NiceAddress *addr;

    if (cand->type == NICE_CANDIDATE_TYPE_RELAYED)
      addr = &cand->addr;
    else
      addr = &cand->base_addr;

    if (nice_address_equal (&nicesock->addr, addr) &&
        local_candidate_and_socket_compatible (agent, cand, nicesock)) {
      local_candidate = cand;
      break;
    }
  }

  for (i = component->remote_candidates; i; i = i->next) {
    NiceCandidate *cand = i->data;
    if (nice_address_equal (from, &cand->addr) &&
        remote_candidate_and_socket_compatible (agent, local_candidate,
        cand, nicesock)) {
      remote_candidate = cand;
      break;
    }
  }

  if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE ||
      agent->compatibility == NICE_COMPATIBILITY_MSN ||
      agent->compatibility == NICE_COMPATIBILITY_OC2007) {
    /* We need to find which local candidate was used */
    for (i = component->remote_candidates;
         i != NULL && remote_candidate2 == NULL; i = i->next) {
      for (j = component->local_candidates; j; j = j->next) {
        gboolean inbound = TRUE;
        NiceCandidate *rcand = i->data;
        NiceCandidate *lcand = j->data;

        /* If we receive a response, then the username is local:remote */
        if (agent->compatibility != NICE_COMPATIBILITY_MSN) {
          if (stun_message_get_class (&req) == STUN_REQUEST ||
              stun_message_get_class (&req) == STUN_INDICATION) {
            inbound = TRUE;
          } else {
            inbound = FALSE;
          }
        }

        uname_len = priv_create_username (agent, stream,
            component->id,  rcand, lcand,
            uname, sizeof (uname), inbound);



        stun_debug ("Comparing usernames of size %d and %d: %d",
            username_len, uname_len, username && uname_len == username_len &&
            memcmp (username, uname, uname_len) == 0);
        stun_debug_bytes ("  First username: ", username,
            username ? username_len : 0);
        stun_debug_bytes ("  Second uname:   ", uname, uname_len);

        if (username &&
            uname_len == username_len &&
            memcmp (uname, username, username_len) == 0) {
          local_candidate = lcand;
          remote_candidate2 = rcand;
          break;
        }
      }
    }
  }

  if (component->remote_candidates &&
      agent->compatibility == NICE_COMPATIBILITY_GOOGLE &&
      local_candidate == NULL &&
      discovery_msg == FALSE) {
    /* if we couldn't match the username and the stun agent has
       IGNORE_CREDENTIALS then we have an integrity check failing.
       This could happen with the race condition of receiving connchecks
       before the remote candidates are added. Just drop the message, and let
       the retransmissions make it work. */
    nice_debug ("Agent %p : Username check failed.", agent);
    return TRUE;
  }

  /* This is most likely caused by a second response to a request which
   * already has received a valid reply.
   */
  if (valid == STUN_VALIDATION_UNMATCHED_RESPONSE) {
    nice_debug ("Agent %p : Valid STUN response for which we don't have a request, ignoring", agent);
    return TRUE;
  }

  if (valid != STUN_VALIDATION_SUCCESS) {
    nice_debug ("Agent %p : STUN message is unsuccessful %d, ignoring", agent, valid);
    return FALSE;
  }


  if (stun_message_get_class (&req) == STUN_REQUEST) {
    if (   agent->compatibility == NICE_COMPATIBILITY_MSN
        || agent->compatibility == NICE_COMPATIBILITY_OC2007) {
      if (local_candidate && remote_candidate2) {
        gsize key_len;

	if (agent->compatibility == NICE_COMPATIBILITY_MSN) {
          username = (uint8_t *) stun_message_find (&req,
	  STUN_ATTRIBUTE_USERNAME, &username_len);
	  uname_len = priv_create_username (agent, stream,
              component->id,  remote_candidate2, local_candidate,
	      uname, sizeof (uname), FALSE);
	  memcpy (username, uname, MIN (uname_len, username_len));

	  req.key = g_base64_decode ((gchar *) remote_candidate2->password,
              &key_len);
          req.key_len = key_len;
	} else if (agent->compatibility == NICE_COMPATIBILITY_OC2007) {
          req.key = g_base64_decode ((gchar *) local_candidate->password,
              &key_len);
          req.key_len = key_len;
	}
      } else {
        nice_debug ("Agent %p : received MSN incoming check from unknown remote candidate. "
            "Ignoring request", agent);
        return TRUE;
      }
    }

    rbuf_len = sizeof (rbuf);
    res = stun_usage_ice_conncheck_create_reply (&component->stun_agent, &req,
        &msg, rbuf, &rbuf_len, &sockaddr.storage, sizeof (sockaddr),
        &control, agent->tie_breaker,
        agent_to_ice_compatibility (agent));

    if (   agent->compatibility == NICE_COMPATIBILITY_MSN
        || agent->compatibility == NICE_COMPATIBILITY_OC2007) {
      g_free (req.key);
    }

    if (res == STUN_USAGE_ICE_RETURN_ROLE_CONFLICT)
      priv_check_for_role_conflict (agent, control);

    if (res == STUN_USAGE_ICE_RETURN_SUCCESS ||
        res == STUN_USAGE_ICE_RETURN_ROLE_CONFLICT) {
      /* case 1: valid incoming request, send a reply/error */
      bool use_candidate =
          stun_usage_ice_conncheck_use_candidate (&req);
      uint32_t priority = stun_usage_ice_conncheck_priority (&req);

      if (agent->compatibility == NICE_COMPATIBILITY_GOOGLE ||
          agent->compatibility == NICE_COMPATIBILITY_MSN ||
          agent->compatibility == NICE_COMPATIBILITY_OC2007)
        use_candidate = TRUE;

      if (stream->initial_binding_request_received != TRUE)
        agent_signal_initial_binding_request_received (agent, stream);

      if (remote_candidate == NULL) {
	nice_debug ("Agent %p : No matching remote candidate for incoming "
            "check -> peer-reflexive candidate.", agent);
	remote_candidate = discovery_learn_remote_peer_reflexive_candidate (
            agent, stream, component, priority, from, nicesock,
            local_candidate,
            remote_candidate2 ? remote_candidate2 : remote_candidate);
        if(remote_candidate && stream->remote_ufrag[0]) {
          if (local_candidate &&
              local_candidate->transport == NICE_CANDIDATE_TRANSPORT_TCP_PASSIVE) {
            CandidateCheckPair *pair;

            pair = priv_conn_check_add_for_candidate_pair_matched (agent,
                stream->id, component, local_candidate, remote_candidate,
                NICE_CHECK_SUCCEEDED);
            if (pair) {
              pair->valid = TRUE;
            }
          } else
            conn_check_add_for_candidate (agent, stream->id, component, remote_candidate);
        }
      }

      nice_component_add_valid_candidate (agent, component, remote_candidate);

      priv_reply_to_conn_check (agent, stream, component, local_candidate,
          remote_candidate, from, nicesock, rbuf_len, &msg, use_candidate);

      if (stream->remote_ufrag[0] == 0) {
        /* case: We've got a valid binding request to a local candidate
         *       but we do not yet know remote credentials.
         *       As per sect 7.2 of ICE (ID-19), we send a reply
         *       immediately but postpone all other processing until
         *       we get information about the remote candidates */

        /* step: send a reply immediately but postpone other processing */
        priv_store_pending_check (agent, component, from, nicesock,
            username, username_len, priority, use_candidate);
        priv_print_conn_check_lists (agent, G_STRFUNC, ", icheck stored");
      }
    } else {
      nice_debug ("Agent %p : Invalid STUN packet, ignoring... %s",
          agent, strerror(errno));
      return FALSE;
    }
  } else {
      /* case 2: not a new request, might be a reply...  */
      gboolean trans_found = FALSE;

      /* note: ICE sect 7.1.2. "Processing the Response" (ID-19) */

      /* step: let's try to match the response to an existing check context */
      if (trans_found != TRUE)
        trans_found = priv_map_reply_to_conn_check_request (agent, stream,
	    component, nicesock, from, local_candidate, remote_candidate, &req);

      /* step: let's try to match the response to an existing discovery */
      if (trans_found != TRUE)
        trans_found = priv_map_reply_to_discovery_request (agent, &req);

      /* step: let's try to match the response to an existing turn allocate */
      if (trans_found != TRUE)
        trans_found = priv_map_reply_to_relay_request (agent, &req);

      /* step: let's try to match the response to an existing turn refresh */
      if (trans_found != TRUE)
        trans_found = priv_map_reply_to_relay_refresh (agent, &req);

      if (trans_found != TRUE)
        trans_found = priv_map_reply_to_relay_remove (agent, &req);

      /* step: let's try to match the response to an existing keepalive conncheck */
      if (trans_found != TRUE)
        trans_found = priv_map_reply_to_keepalive_conncheck (agent, component,
            &req);

      if (trans_found != TRUE)
        nice_debug ("Agent %p : Unable to match to an existing transaction, "
            "probably a keepalive.", agent);
  }

  /* RENOMINATION attribute support */
  conn_check_handle_renomination(agent, stream, component, &req, remote_candidate, local_candidate);

  return TRUE;
}

/* Remove all pointers to the given @sock from the connection checking process.
 * These are entirely NiceCandidates pointed to from various places. */
void
conn_check_prune_socket (NiceAgent *agent, NiceStream *stream, NiceComponent *component,
    NiceSocket *sock)
{
  GSList *l;

  if (component->selected_pair.local &&
      component->selected_pair.local->sockptr == sock &&
      component->state == NICE_COMPONENT_STATE_READY) {
    nice_debug ("Agent %p: Selected pair socket %p has been destroyed, "
        "declaring failed", agent, sock);
    agent_signal_component_state_change (agent,
        stream->id, component->id, NICE_COMPONENT_STATE_FAILED);
  }

  /* Prune from the candidate check pairs. */
  for (l = stream->conncheck_list; l != NULL;) {
    CandidateCheckPair *p = l->data;
    GSList *next = l->next;

    if ((p->local != NULL && p->local->sockptr == sock) ||
        (p->remote != NULL && p->remote->sockptr == sock) ||
        (p->sockptr == sock)) {
      nice_debug ("Agent %p : Retransmissions failed, giving up on pair %p",
          agent, p);
      candidate_check_pair_fail (stream, agent, p);
      candidate_check_pair_free (agent, p);
      stream->conncheck_list = g_slist_delete_link (stream->conncheck_list, l);
    }

    l = next;
  }
}