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
//! TURN over TCP and over TLS built into the engine (RFC 8656 section 3.1; `turns:` and
//! `turn:...?transport=tcp` servers of the configuration), through the stream interface.
//!
//! For each such server the engine asks its driver to resolve the name
//! ([`StreamCommand::Resolve`](shared::stream::StreamCommand::Resolve)) unless it is an
//! address, orders the addresses by Happy Eyeballs (RFC 8305) and connects to them staggered
//! by the Connection Attempt Delay, keeping the first that connects. Over TLS (rustls,
//! sans-I/O, ALPN `stun.turn`) it verifies the server with the roots or verifier the
//! application gave. It then runs the TURN client over the connection (TURN's own framing,
//! RFC 8656 section 12.5), allocates, announces the relayed candidate with its
//! `relayProtocol` (`tcp` or `tls`), creates permissions as the agent sends, and relays the
//! agent's datagrams both ways. The relayed transport itself is UDP (RFC 8656).
//!
//! A `turns:...?transport=udp` server is reached over DTLS (RFC 7350): a client-role
//! `rtci-dtls` association from a UDP host candidate's base, on the application's socket. Its
//! records leave through `poll_write` and are taken out of `handle_read` before ICE sees them
//! (by the server's address on that base); the server's certificate is checked against the
//! URI's host with the same roots or verifier as TLS. The TURN client runs over it with UDP's
//! retransmissions (RFC 7350 section 4), and the relayed candidate's `relayProtocol` is
//! `dtls`.
//!
//! A plain `turn:` server over UDP (`turn:...?transport=udp`, the default transport) is run
//! the same way on the application's socket unless the application gathers its relayed
//! candidates itself (`SettingEngineBuilder::with_relay_gathering`): from each transport's
//! first UDP host candidate's base of the server's family, the engine sends the Allocate
//! through `poll_write` and takes the server's answers out of `handle_read` (by the
//! transactions it has open, and Data indications and ChannelData on its allocation). The
//! server's addresses race as RFC 8656 section 3.9 says for UDP: an unauthenticated Allocate
//! to each, staggered by the Connection Attempt Delay; the first answered keeps going, a later
//! 401 is dropped, and an allocation a later answer made is deleted with a Refresh of LIFETIME
//! 0. Permissions, channel bindings, refreshes and the 401 / 438 paths are the TURN client's
//! (`rtci_turn::client`); the relayed candidate's `relayProtocol` is `udp`.
use super::RTCPeerConnection;
use super::streams::{TURN, tcp_context};
use super::turn_tls::{TlsLayer, TurnTlsConfig};
use crate::peer_connection::handler::transport_set::TransportId;
use crate::peer_connection::servers_in_force::{ServersInForce, same_url};
use crate::peer_connection::transport::ice::candidate::RTCIceServerTransportProtocol;
use bytes::BytesMut;
use ice::url::{ProtoType, SchemeType, Url};
use log::debug;
use sansio::Protocol;
use shared::stream::happy_eyeballs::{
AddressRank, CONNECTION_ATTEMPT_DELAY, HappyEyeballs, sort_addresses_ranked,
};
use shared::stream::{Framing, StreamId, StreamLayer};
use shared::{TaggedBytesMut, TransportContext, TransportProtocol};
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
mod tcp_relay;
/// ALTERNATE-SERVER redirects followed per resolution.
const MAX_REDIRECTS: u8 = 3;
/// How long an Allocate that lost a UDP race (RFC 8656 section 3.9) is waited on past its
/// client's next timer, for an answer that would leave an allocation to delete.
const LOSER_GRACE: Duration = Duration::from_secs(40);
/// Datagrams held per peer address while their permission is being created.
const MAX_HELD_PER_PEER: usize = 32;
/// RFC 8656 section 3.7: "the application MUST assume a Path MTU (PMTU) of 1280 bytes". A Send
/// indication to an IPv6 peer adds 56 bytes (header, XOR-PEER-ADDRESS, DATA, FINGERPRINT) and
/// UDP / IPv6 48 more: 1176 bytes of payload fit, fewer than the engine's DTLS records (1200)
/// and SRTP packets (1216) take; as ChannelData (4 bytes) they fit. So once the relayed pair is
/// selected, data waits for the channel (at most this many datagrams per link) instead of
/// going as Send indications; checks still go at once.
const MAX_HELD_FOR_CHANNEL: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinkState {
/// Not started.
Pending,
/// The driver is looking up the server's NAPTR or SRV records (RFC 5928 section 3).
Discovering(u64),
/// The driver is resolving the host name.
Resolving(u64),
/// Connection attempts are racing.
Connecting,
/// Connected; the TURN client runs on it.
Open(StreamId),
/// The DTLS association is up (`TurnLink::dtls`); the TURN client runs on it.
OpenDtls,
/// Over UDP: an address answered first (`TurnLink::client` runs from `link_local` to
/// `server` on the application's socket).
OpenUdp,
/// Given up: no address connected, TLS failed, the allocation failed or the connection
/// ended.
Failed,
/// Closed once ICE had completed without its relayed candidate (RFC 6544 section 11.2);
/// a new ICE generation allocates again.
Released,
}
/// What carries a link's TURN messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Carrier {
/// TCP (`turn:...?transport=tcp`).
Tcp,
/// TLS over TCP (`turns:`).
Tls,
/// DTLS over the application's UDP socket (`turns:...?transport=udp`, RFC 7350).
Dtls,
/// Plain UDP on the application's socket (`turn:`, `turn:...?transport=udp`).
Udp,
}
/// An unauthenticated Allocate racing to one address of a `turn:` server over UDP (RFC 8656
/// section 3.9), from a UDP base of the transport.
pub(crate) struct UdpAttempt {
/// The link's URL (`TurnLink::url_string`).
url: String,
remote: SocketAddr,
base: SocketAddr,
client: turn::client::Client,
/// Its Allocate has gone out. Not yet while the engine is deleting an allocation of the
/// same 5-tuple (`EngineTurn::five_tuple_in_release`): the request waits for that release
/// to end.
sent: bool,
}
/// Who gathers relayed candidates from `turn:` servers over UDP. See
/// `SettingEngineBuilder::with_relay_gathering`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum RelayGathering {
/// The engine, on the application's UDP socket, for each transport and each `turn:` server
/// over UDP of the configuration (as browsers do). A server for which the application adds
/// a relayed candidate itself is left to it.
#[default]
Engine,
/// The application: the engine sends nothing to a `turn:` server over UDP.
///
/// The application runs the TURN client and adds the relayed candidate
/// (`add_local_candidate`, with `url` set to the server). The engine then treats the
/// relayed address as a local address of its own, and the application carries datagrams
/// between it and the allocation, as the engine does for an allocation it runs itself:
///
/// - **In**: a datagram the allocation relayed (the payload of a Data indication or of
/// ChannelData) goes to `handle_read` with `local_addr` = the relayed address (the relay
/// candidate's address, the XOR-RELAYED-ADDRESS of the Allocate response) and
/// `peer_addr` = the peer (XOR-PEER-ADDRESS, or the channel's peer). Not the address of
/// the socket that talks to the TURN server: the ICE agent matches `local_addr` exactly
/// against its local candidates (RFC 8445 section 7.3.1.4), and a datagram on any other
/// address is discarded ("Discarded message, not a valid local candidate").
/// - **Out**: a datagram from `poll_write` whose `transport.local_addr` is the relayed
/// address leaves through the allocation (a Send indication, or ChannelData on a bound
/// channel, to `transport.peer_addr`; RFC 8656 sections 11 and 12), not from a socket.
///
/// ```text
/// // in: what the TURN client unwrapped
/// pc.handle_read(TaggedBytesMut { now, message: payload, transport: TransportContext {
/// local_addr: relayed_addr, // the relay candidate's address
/// peer_addr: peer, // XOR-PEER-ADDRESS / the channel's peer
/// transport_protocol: TransportProtocol::UDP, ecn: None } })?;
/// // out
/// while let Some(msg) = pc.poll_write() {
/// if msg.transport.local_addr == relayed_addr {
/// turn.send_to(&msg.message, msg.transport.peer_addr)?; // Send / ChannelData
/// } else {
/// socket_for(msg.transport.local_addr).send_to(&msg.message, msg.transport.peer_addr)?;
/// }
/// }
/// ```
Application,
}
/// An allocation over UDP the engine is letting go, or an Allocate still under way when it
/// stopped needing it: its client runs on until the transaction is done (RFC 8656 section 8
/// with RFC 8489 section 6.2.1: the Refresh of LIFETIME 0 is retransmitted, a 438 answered with
/// the new nonce), after `close()` too.
pub(crate) struct UdpRelease {
url: String,
base: SocketAddr,
server: SocketAddr,
client: turn::client::Client,
/// The allocation being deleted; `None` while an Allocate is under way.
relay: Option<SocketAddr>,
/// The Allocate under way carries the credential (its success is an allocation, which is
/// deleted at once); otherwise it is the first, unauthenticated one: a 401 to it ends it,
/// and the request it asks for is not sent.
signed: bool,
done: bool,
}
/// A DTLS association to one address of a `turns:...?transport=udp` server, from a UDP base.
pub(crate) struct DtlsAttempt {
remote: SocketAddr,
base: SocketAddr,
endpoint: dtls::endpoint::Endpoint,
}
impl DtlsAttempt {
/// Moves the association's records onto the application's socket (`poll_write`).
fn flush(&mut self, out: &mut std::collections::VecDeque<TaggedBytesMut>) {
while let Some(t) = self.endpoint.poll_transmit() {
out.push_back(t);
}
}
}
pub(crate) struct TurnLink {
/// The transport the relayed candidate is gathered for: each transport allocates on its
/// own (RFC 9429 section 5.2.1).
transport: TransportId,
url: Url,
carrier: Carrier,
/// Over DTLS: the handshakes racing, one per server address.
dtls_attempts: Vec<DtlsAttempt>,
/// Over DTLS: the association that won.
dtls: Option<DtlsAttempt>,
/// Over UDP: the Allocates racing, one per server address.
udp_attempts: Vec<UdpAttempt>,
/// A TCP allocation (RFC 6062): relayed TCP candidates, peers on data connections.
relay_tcp: bool,
/// Its peers' data connections.
data: Vec<tcp_relay::DataConn>,
/// The peer addresses it has created a permission for.
permitted: HashSet<IpAddr>,
state: LinkState,
race: Option<HappyEyeballs>,
attempts: Vec<StreamId>,
client: Option<turn::client::Client>,
server: Option<SocketAddr>,
link_local: Option<SocketAddr>,
relay: Option<SocketAddr>,
/// The other relayed address of a dual allocation (ADDITIONAL-ADDRESS-FAMILY, RFC 8656
/// section 7.1): the IPv6 one beside `relay`, when the server gave both.
relay_more: Vec<SocketAddr>,
/// The ICE generation (local ufrag) the relayed candidate was last announced for.
announced_ufrag: Option<String>,
/// The name's query, while its per-family answers may still come.
query: Option<u64>,
/// The NAPTR / SRV discovery of a server whose URI gives no port.
discovery: Option<crate::peer_connection::dns_discovery::Discovery>,
held: HashMap<IpAddr, Vec<(SocketAddr, Vec<u8>)>>,
/// The ICE generation (local ufrag) the link last started for: a failed or released link
/// starts over, from the resolution, for a new one (RFC 5928 section 3).
generation: Option<String>,
/// ALTERNATE-SERVER redirects followed in this resolution (RFC 8489 section 10: at most
/// a few, against loops).
redirects: u8,
/// The servers this resolution's Allocate went to, against a redirection back to one of
/// them (RFC 8489 section 10).
redirect_guard: stun::alternate::RedirectGuard,
/// Data (not checks) for a peer whose channel is being bound, after ICE selected the pair
/// through this relay: it goes as ChannelData once the channel is bound, so that it fits a
/// 1280-byte path MTU (RFC 8656 section 3.7, [`MAX_HELD_FOR_CHANNEL`]).
channel_held: Vec<(SocketAddr, Vec<u8>)>,
/// A `turn:` link over UDP made for one more UDP base of its transport (RFC 8828 section
/// 5.2, Mode 1: every interface reaches the TURN server): it allocates only from a base no
/// other link to the server uses, and fails when there is none.
extra_base: bool,
/// The ALTERNATE-DOMAIN of the (authenticated) 300 this link followed: the name the
/// alternate server's certificate is checked against over TLS or DTLS (RFC 8489 section
/// 10). `None`: the URI's host.
alternate_domain: Option<String>,
/// A link whose server left the list a new ICE generation took (new credentials, say)
/// while its relayed candidate carried the data: kept, refreshed and relaying, until the
/// agent no longer uses that path (RFC 8445 section 9: "during the restart, data can
/// continue to be sent using existing data sessions"; section 5.1.1.4), then released.
retiring: bool,
/// The ICE generation (local ufrag) whose start retired the link: a rollback of that
/// generation's local offer brings the link back (RFC 9429 section 5.7).
retired_for: Option<String>,
/// The ICE generation a link was made for when it replaced a link kept retiring (a new
/// DTLS association): a rollback of that generation's local offer drops it.
created_for: Option<String>,
}
impl TurnLink {
fn new(transport: TransportId, url: Url, carrier: Carrier, relay_tcp: bool) -> Self {
Self {
transport,
url,
carrier,
dtls_attempts: vec![],
dtls: None,
udp_attempts: vec![],
relay_tcp,
data: vec![],
permitted: HashSet::new(),
state: LinkState::Pending,
race: None,
attempts: vec![],
client: None,
server: None,
link_local: None,
relay: None,
relay_more: vec![],
announced_ufrag: None,
query: None,
discovery: None,
held: HashMap::new(),
generation: None,
redirects: 0,
redirect_guard: stun::alternate::RedirectGuard::new(),
extra_base: false,
channel_held: vec![],
alternate_domain: None,
retiring: false,
retired_for: None,
created_for: None,
}
}
/// A link not started yet, to `url` over `carrier` for `transport`.
fn pending(transport: TransportId, url: Url, carrier: Carrier, relay_tcp: bool) -> Self {
Self::new(transport, url, carrier, relay_tcp)
}
/// The relayed addresses of the allocation: `relay`, and the second of a dual one.
fn relays(&self) -> impl Iterator<Item = SocketAddr> + '_ {
self.relay
.into_iter()
.chain(self.relay_more.iter().copied())
}
/// Whether `addr` is a relayed address of the allocation.
fn is_relay(&self, addr: SocketAddr) -> bool {
self.relays().any(|r| r == addr)
}
fn settled(&self) -> bool {
matches!(self.state, LinkState::Failed | LinkState::Released) || self.relay.is_some()
}
/// The name the server's certificate is checked against (RFC 8489 sections 6.2.3 and
/// 10): the ALTERNATE-DOMAIN of a redirect when there was one, else the URI's host.
fn certificate_name(&self) -> &str {
self.alternate_domain.as_deref().unwrap_or(&self.url.host)
}
fn url_string(&self) -> String {
let (scheme, transport) = match self.carrier {
Carrier::Tcp => ("turn", "tcp"),
Carrier::Tls => ("turns", "tcp"),
Carrier::Dtls => ("turns", "udp"),
Carrier::Udp => ("turn", "udp"),
};
format!(
"{scheme}:{}:{}?transport={transport}",
host_for_url(&self.url.host),
self.url.port
)
}
fn protocol(&self) -> RTCIceServerTransportProtocol {
match self.carrier {
Carrier::Tcp => RTCIceServerTransportProtocol::Tcp,
Carrier::Tls => RTCIceServerTransportProtocol::Tls,
Carrier::Dtls => RTCIceServerTransportProtocol::Dtls,
Carrier::Udp => RTCIceServerTransportProtocol::Udp,
}
}
/// Whether the link runs on the application's UDP socket (DTLS or plain UDP).
fn on_datagrams(&self) -> bool {
matches!(self.carrier, Carrier::Dtls | Carrier::Udp)
}
fn tls(&self) -> bool {
self.carrier == Carrier::Tls
}
/// The DTLS association (racing or won) to `remote` from `base`.
fn dtls_to(&mut self, base: SocketAddr, remote: SocketAddr) -> Option<&mut DtlsAttempt> {
self.dtls
.iter_mut()
.chain(self.dtls_attempts.iter_mut())
.find(|a| a.base == base && a.remote == remote)
}
}
/// Whether the URL an application gave a relayed candidate names `server` (scheme, host and
/// port; `turn:host` without a port is 3478).
/// The `turn:` / `turns:` URLs of `urls`: `turns:` over UDP is DTLS (RFC 7350 section 4);
/// `turn:` over UDP runs unless the application gathers its relayed candidates itself
/// (`relay_gathering`).
fn turn_servers(urls: &[Url]) -> Vec<Url> {
urls.iter()
.filter(|u| matches!(u.scheme, SchemeType::Turn | SchemeType::Turns))
.cloned()
.collect()
}
fn same_server(url: &str, server: &Url) -> bool {
Url::parse_url(url).is_ok_and(|u| {
u.scheme == server.scheme
&& u.proto == server.proto
&& u.host.eq_ignore_ascii_case(&server.host)
&& u.port == server.port
})
}
fn host_for_url(host: &str) -> String {
if host.contains(':') {
format!("[{host}]")
} else {
host.to_owned()
}
}
/// The engine's TURN-over-stream links.
pub(crate) struct EngineTurn {
/// The servers each transport allocates on: `turn:...?transport=tcp` and `turns:` URLs
/// (`turns:...?transport=udp` over DTLS), and `turn:` over UDP; as each ICE generation of
/// each transport took them (`RTCPeerConnection::set_configuration` gives the next
/// generations a new list).
servers: ServersInForce,
/// The bases of the UDP host candidates of each transport: where a DTLS link starts.
udp_bases: Vec<(TransportId, SocketAddr)>,
/// Relayed UDP addresses of allocations that were lost (`turn_allocation_lost`): the
/// agent may still write from their candidate (the selected pair until the restart selects
/// another); those writes go nowhere rather than out of the application's socket from an
/// address that is not its own. An allocation that gets such an address again takes it
/// back.
dead_relays: HashSet<SocketAddr>,
/// The transports whose links were made (once each, failed ones are not made again).
made_for: HashSet<TransportId>,
links: Vec<TurnLink>,
pub(crate) enabled: bool,
tls: TurnTlsConfig,
tls_config: Option<std::sync::Arc<rustls::ClientConfig>>,
/// Relayed TCP candidates from a TCP allocation beside the UDP one, for each server over
/// TCP or TLS (RFC 6544 section 5.5).
pub(crate) tcp_relay: bool,
/// The addresses of the remote TCP candidates signalled per transport (for the
/// permissions of the TCP allocations).
remote_tcp_ips: Vec<(TransportId, IpAddr)>,
/// Server addresses not to be used before an instant: an Allocate answered 486 or 508
/// (one minute) or 437 (two minutes), RFC 8656 section 7.4 with RFC 5928 section 3 ("MUST
/// NOT be used for the specified duration, even if returned by a subsequent resolution").
held_back: Vec<(SocketAddr, Instant)>,
/// Who gathers from `turn:` servers over UDP.
pub(crate) relay_gathering: RelayGathering,
/// Allocates that lost a UDP race (RFC 8656 section 3.9), kept until their answer: a 401
/// drops them, a success has the allocation deleted.
udp_losers: Vec<UdpAttempt>,
/// The relayed candidates the application added itself over UDP: the transport and the
/// `url` it gave (`None`: any server).
application_relays: Vec<(TransportId, Option<String>)>,
/// Allocations being let go and Allocates nobody needs any more (`UdpRelease`).
releases: Vec<UdpRelease>,
/// 5-tuples an Allocate was refused with 437 on (RFC 8656 section 7.4): (base, server,
/// until). A link does not allocate from such a base to that server again for two
/// minutes.
mismatched: Vec<(SocketAddr, SocketAddr, Instant)>,
/// 5-tuples whose release ended: (base, server, the instant a new Allocate may leave from
/// it: the end plus `SettingEngine::turn_reallocation_delay`).
freed: Vec<(SocketAddr, SocketAddr, Instant)>,
/// Servers an Allocate was refused by in a way RFC 8656 section 7.4 (and 7.3) says not to
/// retry "until it believes the problem has been fixed": no link allocates on them again,
/// in any later ICE generation, from any new client ([`TurnRefusal`]).
refused: Vec<TurnRefusal>,
/// The credentials servers accepted an allocation with (realm, nonce, password
/// algorithm, per server address and login): RFC 8489 section 9.2.3.2, "The client
/// SHOULD cache the username, password, realm, and nonce for subsequent communications
/// with the server". A later allocation to the same server with the same login starts
/// with them (`seed_turn_client`), one round trip less than the first request's 401.
accepted_credentials: Vec<turn::client::CachedCredential>,
}
/// A server the engine does not ask for an allocation again (RFC 8656 sections 7.3 and 7.4).
/// A refusal of the credentials (401 after they were sent, 441) lasts while the configuration
/// gives that server the same user name and password (RFC 8489 section 9.2.5: no retry
/// "without changing the username, realm, or password"); the others (400, 403, 440, 442, an
/// allocation of a family that was not asked for) last until the application sets a
/// configuration again (`set_servers`), which is its way of saying the problem is fixed.
struct TurnRefusal {
server: SocketAddr,
username: String,
password: String,
of_credentials: bool,
}
/// Most credentials `EngineTurn::accepted_credentials` keeps (one per server and login).
const MAX_CACHED_CREDENTIALS: usize = 16;
impl EngineTurn {
/// The links of the `turn:...?transport=tcp` and `turns:` URLs among `urls`.
pub(crate) fn new(urls: &[Url], enabled: bool, tls: TurnTlsConfig) -> Self {
let servers = ServersInForce::new(turn_servers(urls));
let tls_config = tls.client_config().ok().flatten();
Self {
servers,
udp_bases: vec![],
dead_relays: HashSet::new(),
made_for: HashSet::new(),
links: vec![],
enabled,
tls,
tls_config,
tcp_relay: true,
remote_tcp_ips: vec![],
held_back: vec![],
relay_gathering: RelayGathering::Engine,
udp_losers: vec![],
application_relays: vec![],
releases: vec![],
mismatched: vec![],
freed: vec![],
refused: vec![],
accepted_credentials: vec![],
}
}
/// Has `client` start its Allocate with the credential its server accepted an earlier
/// allocation of this connection with, when one with its login is cached (RFC 8489
/// section 9.2.3.2); the client checks the server and the login itself.
pub(crate) fn seed_turn_client(&self, client: &mut turn::client::Client) {
for cached in self.accepted_credentials.iter().rev() {
if client.use_cached_credential(cached) {
debug!(
"TURN {}: the Allocate carries the cached realm and nonce",
cached.server()
);
return;
}
}
}
/// Caches the credential a server accepted an allocation with, replacing the one of the
/// same server and login.
pub(crate) fn remember_turn_credential(&mut self, cached: turn::client::CachedCredential) {
self.accepted_credentials
.retain(|c| !c.is_for_same_server_and_login(&cached));
if self.accepted_credentials.len() >= MAX_CACHED_CREDENTIALS {
self.accepted_credentials.remove(0);
}
self.accepted_credentials.push(cached);
}
/// Whether the engine runs links over `carrier`: over UDP when it gathers relayed
/// candidates itself, over the others when it runs TURN over streams and DTLS.
fn runs(&self, carrier: Carrier) -> bool {
match carrier {
Carrier::Udp => self.relay_gathering == RelayGathering::Engine,
_ => self.enabled,
}
}
/// Whether the application added a relayed candidate itself for `link`'s server on its
/// transport (by the candidate's `url`, or any relayed candidate without one).
fn left_to_application(&self, link: &TurnLink) -> bool {
link.carrier == Carrier::Udp
&& self.application_relays.iter().any(|(t, url)| {
*t == link.transport && url.as_deref().is_none_or(|u| same_server(u, &link.url))
})
}
/// Whether an Allocate from `base` to `server` was refused with 437 less than two minutes
/// before `now`.
fn is_mismatched(&self, base: SocketAddr, server: SocketAddr, now: Instant) -> bool {
self.mismatched
.iter()
.any(|(b, s, until)| *b == base && *s == server && now < *until)
}
/// Whether an allocation of the 5-tuple (`base`, `server`) is being deleted at `now`: a
/// release of it is under way (`UdpRelease`), or ended less than the reallocation delay
/// before. Until the server has answered the Refresh of LIFETIME 0 the allocation is the
/// 5-tuple's, and an Allocate on it would be refused with 437 (RFC 8656 section 7.2, step
/// 2), after which the client leaves the server alone for two minutes (section 7.4).
fn five_tuple_in_release(&self, base: SocketAddr, server: SocketAddr, now: Instant) -> bool {
self.releases
.iter()
.any(|r| !r.done && r.base == base && r.server == server)
|| self
.freed
.iter()
.any(|(b, s, at)| *b == base && *s == server && now < *at)
}
/// Whether a retiring link still holds its allocation on the 5-tuple (`base`, `server`):
/// kept for the data or for a rollback of the restart (`turn_free_udp_base`).
fn five_tuple_held(&self, base: SocketAddr, server: SocketAddr) -> bool {
self.links.iter().any(|l| {
l.retiring
&& l.client.is_some()
&& l.carrier == Carrier::Udp
&& l.link_local == Some(base)
&& l.server == Some(server)
})
}
/// Whether a link on datagrams uses, or is trying, the 5-tuple (`base`, `server`).
fn five_tuple_used(&self, base: SocketAddr, server: SocketAddr) -> bool {
self.links.iter().any(|l| {
l.on_datagrams()
&& ((l.link_local == Some(base) && l.server == Some(server))
|| l.udp_attempts
.iter()
.any(|a| a.base == base && a.remote == server)
|| l.dtls_attempts
.iter()
.any(|a| a.base == base && a.remote == server))
})
}
/// How many links there are (RFC 8445 section 14.3, `gathering_rto`).
pub(crate) fn link_count(&self) -> usize {
self.links.len()
}
/// Whether `server` is held back at `now`.
fn is_held_back(&self, server: SocketAddr, now: Instant) -> bool {
self.held_back
.iter()
.any(|(a, until)| *a == server && now < *until)
}
/// The configuration's new servers: the ICE generations that begin from now on allocate
/// on them (W3C webrtc-pc "set the configuration", RFC 9429 section 4.1.18).
pub(crate) fn set_servers(&mut self, urls: &[Url]) {
self.servers.set(turn_servers(urls));
self.refused.retain(|r| r.of_credentials);
}
/// Whether `server` refused an allocation to `url`'s credentials for good
/// ([`TurnRefusal`]).
fn is_refused(&self, server: SocketAddr, url: &Url) -> bool {
self.refused.iter().any(|r| {
r.server == server
&& (!r.of_credentials || (r.username == url.username && r.password == url.password))
})
}
/// The links of `transport` for its generation `ufrag`, one per server of the list that
/// generation takes: made once per transport, and when a later generation takes another
/// list, the links of servers no longer in it are returned (to be closed) and links for
/// the new servers are made.
fn make_links(&mut self, transport: TransportId, ufrag: &str) -> Vec<TurnLink> {
let (servers, new_phase) = self.servers.for_generation(transport, ufrag);
let first = self.made_for.insert(transport);
if !first && !new_phase {
return vec![];
}
let mut dropped = vec![];
if !first {
let mut i = 0;
while i < self.links.len() {
if self.links[i].transport == transport
&& !self.links[i].retiring
&& !servers.iter().any(|u| same_url(u, &self.links[i].url))
{
dropped.push(self.links.remove(i));
} else {
i += 1;
}
}
}
for url in &servers {
if !first
&& self
.links
.iter()
.any(|l| l.transport == transport && !l.retiring && same_url(&l.url, url))
{
continue;
}
let carrier = match (url.scheme, url.proto) {
(SchemeType::Turns, ProtoType::Udp) => Carrier::Dtls,
(SchemeType::Turns, _) => Carrier::Tls,
(_, ProtoType::Udp) => Carrier::Udp,
_ => Carrier::Tcp,
};
if !self.runs(carrier) {
continue;
}
// Over TCP and TLS also a TCP allocation, on a control connection of its own (an
// allocation is its 5-tuple's, RFC 8656 section 2.2), for relayed TCP candidates.
let kinds: &[bool] = if self.tcp_relay && matches!(carrier, Carrier::Tcp | Carrier::Tls)
{
&[false, true]
} else {
&[false]
};
for &relay_tcp in kinds {
self.links
.push(TurnLink::new(transport, url.clone(), carrier, relay_tcp));
}
}
dropped
}
/// RFC 8828 section 5.2, Mode 1: "WebRTC MUST use all network interfaces to attempt
/// communication with STUN servers, TURN servers, or peers." Each `turn:` server over UDP
/// or DTLS of `transport` gets a link per usable UDP base (`usable`), one allocation from
/// each
/// interface the application gave a host candidate on; the links beyond the first are
/// `extra_base`.
fn add_links_for_bases(&mut self, transport: TransportId, usable: usize) {
let mut urls: Vec<(Url, Carrier)> = vec![];
for l in self.links.iter().filter(|l| {
l.transport == transport && l.on_datagrams() && !l.retiring && !l.extra_base
}) {
if !urls.iter().any(|(u, _)| same_url(u, &l.url)) {
urls.push((l.url.clone(), l.carrier));
}
}
for (url, carrier) in urls {
let have = self
.links
.iter()
.filter(|l| {
l.transport == transport
&& l.carrier == carrier
&& !l.retiring
&& same_url(&l.url, &url)
})
.count();
for _ in have..usable {
let mut link = TurnLink::new(transport, url.clone(), carrier, false);
link.extra_base = true;
self.links.push(link);
}
}
}
/// Whether a link of `transport` is still on its way to a relayed candidate. A link over
/// a stream waits for the driver (`driver`: one serves the stream interface); a DTLS link
/// needs it only to resolve a name.
pub(crate) fn pending(&self, transport: TransportId, driver: bool) -> bool {
self.links.iter().any(|l| {
self.runs(l.carrier)
&& l.transport == transport
&& l.state != LinkState::Pending
&& !l.settled()
&& (driver
|| (l.on_datagrams()
&& !matches!(l.state, LinkState::Resolving(_) | LinkState::Discovering(_))))
})
}
/// A UDP host candidate's base of `transport`: DTLS links of the transport can start.
pub(crate) fn note_udp_base(&mut self, transport: TransportId, base: SocketAddr) {
if !self.udp_bases.contains(&(transport, base)) {
self.udp_bases.push((transport, base));
}
}
/// The Allocate of a link of `transport` (UDP relaying; a TCP allocation takes
/// `tcp_relay::tcp_allocation`). RFC 6544 section 5: "If the local network or host does
/// not support IPv6 addressing, then clients SHOULD make use of other techniques, e.g.,
/// TURN-IPv6 [RFC6156] ... for obtaining IPv6 candidates." When the host candidates the
/// application gave for the transport are all IPv4, the Allocate also asks for an IPv6
/// relayed address (ADDITIONAL-ADDRESS-FAMILY, RFC 8656 section 7.1); a server that has
/// none gives the IPv4 one alone. With no host candidate yet nothing is known of the
/// host's families, and the Allocate asks for the IPv4 address only.
fn allocate_options(&self, transport: TransportId) -> turn::client::AllocateOptions {
let mut bases = self
.udp_bases
.iter()
.filter(|(t, _)| *t == transport)
.map(|(_, b)| b);
let ipv4_only = bases.clone().next().is_some() && !bases.any(SocketAddr::is_ipv6);
turn::client::AllocateOptions {
additional_ipv6: ipv4_only,
..Default::default()
}
}
/// The first UDP base of `transport` of the family of `server` that is `usable`.
fn udp_base(
&self,
transport: TransportId,
server: SocketAddr,
usable: impl Fn(SocketAddr) -> bool,
) -> Option<SocketAddr> {
self.udp_bases
.iter()
.find(|(t, b)| *t == transport && b.is_ipv4() == server.is_ipv4() && usable(*b))
.map(|(_, b)| *b)
}
/// The UDP link whose client runs, or one of whose Allocates races, from `base` to
/// `remote`.
fn link_of_udp(&self, base: SocketAddr, remote: SocketAddr) -> Option<usize> {
self.links.iter().position(|l| {
l.carrier == Carrier::Udp
&& ((l.state == LinkState::OpenUdp
&& l.link_local == Some(base)
&& l.server == Some(remote))
|| l.udp_attempts
.iter()
.any(|a| a.base == base && a.remote == remote))
})
}
/// The DTLS link (and whether its association has won) that `(base, remote)` is one of.
fn link_of_dtls(&self, base: SocketAddr, remote: SocketAddr) -> Option<usize> {
self.links.iter().position(|l| {
l.dtls
.iter()
.chain(l.dtls_attempts.iter())
.any(|a| a.base == base && a.remote == remote)
})
}
fn link_of_stream(&self, id: StreamId) -> Option<usize> {
self.links
.iter()
.position(|l| l.state == LinkState::Open(id) || l.attempts.contains(&id))
}
/// Whether a TCP allocation has its relayed address.
pub(crate) fn has_tcp_relay(&self) -> bool {
self.links.iter().any(|l| l.relay_tcp && l.relay.is_some())
}
/// Whether `addr` is the relayed UDP address of an allocation that was lost.
pub(crate) fn is_dead_relay(&self, addr: SocketAddr) -> bool {
self.dead_relays.contains(&addr)
}
/// The link whose relayed UDP address is `addr`.
pub(crate) fn link_of_relay(&self, addr: SocketAddr) -> Option<usize> {
self.links
.iter()
.position(|l| !l.relay_tcp && l.is_relay(addr))
}
/// The links and their relayed addresses, for diagnostics.
pub(crate) fn relays(&self) -> Vec<SocketAddr> {
self.links.iter().flat_map(TurnLink::relays).collect()
}
pub(crate) fn tls_config(&self) -> &TurnTlsConfig {
&self.tls
}
}
/// Lets go of what a UDP link holds: its allocation is deleted with a Refresh of LIFETIME 0
/// (RFC 8656 section 8), run as a transaction of its own (`UdpRelease`), and an Allocate still
/// under way (one racing, or the request with the credential) is followed to its answer, a
/// success deleted. The link keeps no client.
fn release_udp_allocation(
link: &mut TurnLink,
now: Instant,
out: &mut std::collections::VecDeque<TaggedBytesMut>,
releases: &mut Vec<UdpRelease>,
) {
if link.carrier != Carrier::Udp {
return;
}
let url = link.url_string();
// An Allocate that never left (it waited for a release of its 5-tuple) has nothing to
// follow.
for a in link.udp_attempts.drain(..).filter(|a| a.sent) {
releases.push(UdpRelease {
url: a.url,
base: a.base,
server: a.remote,
client: a.client,
relay: None,
signed: false,
done: false,
});
}
if link.state != LinkState::OpenUdp {
return;
}
let (Some(base), Some(server)) = (link.link_local, link.server) else {
return;
};
let Some(mut client) = link.client.take() else {
return;
};
let relay = link.relay;
if let Some(relay) = relay
&& let Ok(mut r) = client.relay(relay)
{
let _ = r.close(now);
}
while let Some(t) = client.poll_write() {
out.push_back(TaggedBytesMut {
now,
transport: udp_context(base, server),
message: t.message,
});
}
releases.push(UdpRelease {
url,
base,
server,
client,
relay,
signed: true,
done: false,
});
}
fn udp_context(local: SocketAddr, peer: SocketAddr) -> TransportContext {
TransportContext {
local_addr: local,
peer_addr: peer,
transport_protocol: TransportProtocol::UDP,
ecn: None,
}
}
/// The STUN class of a datagram that is a STUN message (RFC 8489 section 5): 0 request, 1
/// indication, 2 success response, 3 error response.
fn stun_class(datagram: &[u8]) -> Option<u8> {
if datagram.len() < 20 || datagram[0] & 0xc0 != 0 || datagram[4..8] != [0x21, 0x12, 0xa4, 0x42]
{
return None;
}
let t = u16::from_be_bytes([datagram[0], datagram[1]]);
Some((((t >> 7) & 0x2) | ((t >> 4) & 0x1)) as u8)
}
fn any_of_family(addr: SocketAddr) -> SocketAddr {
if addr.is_ipv4() {
SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)
} else {
SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0)
}
}
impl RTCPeerConnection {
/// Starts the links not started yet, once there is a local description, and announces
/// the relayed candidates again for a new ICE generation.
pub(crate) fn start_turn_links(&mut self) {
if !(self.streams.turn.enabled
|| self.streams.turn.relay_gathering == RelayGathering::Engine)
|| self.is_closed()
|| self.local_description().is_none()
{
return;
}
self.release_retired_turn_links();
// Again for the links already retiring: an ICE restart taken back
// (`Agent::revert_restart`) restores a session as it was before the withdrawal.
let retiring: Vec<(TransportId, SocketAddr, bool)> = self
.streams
.turn
.links
.iter()
.filter(|l| l.retiring)
.flat_map(|l| l.relays().map(|r| (l.transport, r, l.relay_tcp)))
.collect();
for (transport, relay, tcp) in retiring {
self.withdraw_relay_candidate(transport, relay, tcp);
}
let mut dropped = vec![];
for transport in self.pipeline_context.transports.ids() {
let ufrag = self
.ice_transport_of(transport)
.agent
.get_local_credentials()
.ufrag
.clone();
dropped.extend(self.streams.turn.make_links(transport, &ufrag));
}
// A dropped link whose relayed candidate carries the data stays until the restart has
// its own path (RFC 8445 section 9); so does every dropped link while the local offer
// that restarted ICE is not answered: a rollback of the offer brings its session back,
// allocations included (RFC 9429 section 5.7, `revert_turn_generation`). The others
// close.
let mut closed = vec![];
for mut link in dropped {
let uncommitted = self.restart_uncommitted(link.transport);
if self.turn_relay_carries_data(&link) || (uncommitted && link.client.is_some()) {
debug!(
"{}: kept while its relayed candidate carries the data or the restart is not answered",
link.url
);
// Its relayed candidate is the previous path's only: a restart that keeps the
// local candidates would carry it into the new session, which would pair (and
// nominate) it, and the allocation of the credentials just replaced would never
// be let go (`Agent::withdraw_local_candidate`).
for relay in link.relays().collect::<Vec<_>>() {
self.withdraw_relay_candidate(link.transport, relay, link.relay_tcp);
}
link.retiring = true;
link.retired_for = Some(
self.ice_transport_of(link.transport)
.agent
.get_local_credentials()
.ufrag
.clone(),
);
self.streams.turn.links.push(link);
} else {
closed.push(link);
}
}
self.close_turn_links(closed);
let now = self.pipeline_context.now;
let driver = self.streams.driver_seen;
for index in 0..self.streams.turn.links.len() {
let link = &self.streams.turn.links[index];
// A link over a stream starts for a driver that serves the stream interface; a
// DTLS or UDP link from a UDP host candidate's base, once the transport has one (of
// the server's family, for a server given by address: a link started on a base of
// the other family would fail for good, and the application may add its host
// candidates in any order).
// A UDP link for a server the application gathers from itself never starts.
// An IPv4 address on an IPv6-only host waits for the NAT64 prefix, and with one
// is reached from an IPv6 base (RFC 8305 section 7.1).
let literal = link.url.host.parse::<IpAddr>().ok();
let nat64 = &self.streams.nat64;
let v4_literal = literal.is_some_and(|ip| ip.is_ipv4());
if link.state != LinkState::Pending
|| self.streams.turn.left_to_application(link)
|| (!link.on_datagrams() && !driver)
|| (v4_literal && nat64.waiting())
|| (link.on_datagrams()
&& !self.streams.turn.udp_bases.iter().any(|(t, b)| {
*t == link.transport
&& self.turn_base_usable(*t, *b)
&& literal.is_none_or(|ip| {
ip.is_ipv6() == b.is_ipv6()
|| (ip.is_ipv4() && b.is_ipv6() && nat64.synthesizes())
})
}))
{
continue;
}
let generation = self
.ice_transport_of(self.streams.turn.links[index].transport)
.agent
.get_local_credentials()
.ufrag
.clone();
let link = &mut self.streams.turn.links[index];
link.generation = Some(generation);
link.redirects = 0;
link.alternate_domain = None;
link.redirect_guard = stun::alternate::RedirectGuard::new();
// A link for one more interface takes its server's address from the first link
// (`drive_turn_races`): it resolves nothing itself.
if link.extra_base {
link.race = None;
link.state = LinkState::Connecting;
continue;
}
match link.url.host.parse::<IpAddr>() {
Ok(ip) => {
// With a NAT64 prefix, the synthesized IPv6 addresses first (RFC 8305
// section 7.1).
let addresses = self
.streams
.nat64
.addresses_for(SocketAddr::new(ip, link.url.port));
let link = &mut self.streams.turn.links[index];
link.race = Some(HappyEyeballs::new(
sort_addresses_ranked(&addresses, true, |_| AddressRank::default()),
CONNECTION_ATTEMPT_DELAY,
));
link.state = LinkState::Connecting;
}
// RFC 5928 section 3: without a port, S-NAPTR and SRV find the server.
Err(_) if !link.url.explicit_port => {
// RFC 5928 section 3 and RFC 7350 section 4.2: the S-NAPTR tag and SRV
// service of the transport.
let (tag, srv) = match link.carrier {
Carrier::Tcp => ("turn.tcp", "_turn._tcp"),
Carrier::Tls => ("turn.tls", "_turns._tcp"),
Carrier::Dtls => ("turn.dtls", "_turns._udp"),
Carrier::Udp => ("turn.udp", "_turn._udp"),
};
let discovery = crate::peer_connection::dns_discovery::Discovery::new(
&link.url.host,
link.url.port,
Some(tag),
srv,
);
let first = discovery.start();
link.discovery = Some(discovery);
self.turn_discovery_next(index, first, now);
}
Err(_) => {
let query = self
.streams
.table
.resolve(link.url.host.clone(), link.url.port);
let link = &mut self.streams.turn.links[index];
link.state = LinkState::Resolving(query);
link.query = Some(query);
}
}
}
// A link released once ICE had completed allocates again for a new ICE generation.
for i in 0..self.streams.turn.links.len() {
let l = &self.streams.turn.links[i];
if l.retiring || !matches!(l.state, LinkState::Released | LinkState::Failed) {
continue;
}
let ufrag = self
.ice_transport_of(l.transport)
.agent
.get_local_credentials()
.ufrag
.clone();
// RFC 5928 section 3: "After an allocation succeeds or all the allocations fail,
// the resolution context MUST be discarded, and the resolution algorithm MUST be
// restarted from the beginning for any subsequent allocation."
let last = if l.state == LinkState::Released {
l.announced_ufrag.as_ref()
} else {
l.generation.as_ref()
};
if last.is_some_and(|g| *g != ufrag) {
let l = &mut self.streams.turn.links[i];
l.state = LinkState::Pending;
l.race = None;
l.query = None;
l.discovery = None;
l.announced_ufrag = None;
}
}
self.drive_turn_races(now);
let again: Vec<usize> = self
.streams
.turn
.links
.iter()
.enumerate()
.filter(|(_, l)| {
let ufrag = &self
.ice_transport_of(l.transport)
.agent
.get_local_credentials()
.ufrag;
!l.retiring && l.relay.is_some() && l.announced_ufrag.as_ref() != Some(ufrag)
})
.map(|(i, _)| i)
.collect();
for index in again {
self.announce_relay_candidate(index);
}
}
/// Starts the connection attempts that are due.
pub(crate) fn drive_turn_races(&mut self, now: Instant) {
for index in 0..self.streams.turn.links.len() {
if self.streams.turn.links[index].state != LinkState::Connecting {
continue;
}
// A link for one more interface (`extra_base`) waits for its server's first link:
// once that has its allocation, it allocates on the same server address from
// another base of that family; if that failed, so has this one.
if self.streams.turn.links[index].extra_base {
let link = &self.streams.turn.links[index];
let primary = self.streams.turn.links.iter().find(|l| {
l.transport == link.transport
&& l.carrier == link.carrier
&& !l.extra_base
&& !l.retiring
&& same_url(&l.url, &link.url)
});
match primary.map(|p| (p.state, p.server)) {
Some((LinkState::OpenUdp | LinkState::OpenDtls, Some(server))) => {
// No other interface of the server's family: nothing to do, quietly.
let transport = link.transport;
let turn = &self.streams.turn;
let free = turn.udp_base(transport, server, |b| {
self.turn_base_usable(transport, b) && !turn.five_tuple_used(b, server)
});
let idle = {
let l = &self.streams.turn.links[index];
l.udp_attempts.is_empty()
&& l.dtls_attempts.is_empty()
&& l.dtls.is_none()
&& l.client.is_none()
};
if free.is_none() && idle {
self.streams.turn.links[index].state = LinkState::Failed;
continue;
}
let link = &mut self.streams.turn.links[index];
if idle {
link.race =
Some(HappyEyeballs::new(vec![server], CONNECTION_ATTEMPT_DELAY));
}
}
Some((LinkState::Failed | LinkState::Released, _)) | None => {
self.streams.turn.links[index].state = LinkState::Failed;
continue;
}
_ => continue,
}
}
// An address skipped before anything was sent to it (address policy, held back,
// refused for good) generated no transaction: the next one is still the first.
let mut first_skipped = false;
loop {
// RFC 8445 section 5.1.1.2: "the agent SHOULD NOT generate transactions more
// frequently than one every Ta milliseconds", shared with the server-reflexive
// Binding requests (`srflx.rs`). A server's first attempt waits for the gate;
// the attempts after it within one race are paced by Happy Eyeballs (250 ms), and
// one that follows a failed attempt starts at once (RFC 8305 section 5): "first"
// is the race's first start, not an empty list of attempts after a failure.
// Only an attempt that sends takes the Ta slot: a server skipped unasked does
// not hold back the next transaction.
let first = first_skipped || {
let l = &self.streams.turn.links[index];
!l.race.as_ref().is_some_and(HappyEyeballs::started)
&& l.client.is_none()
&& l.redirects == 0
};
if first && self.streams.srflx.ta_gate_closed(now) {
break;
}
let Some(addr) = self.streams.turn.links[index]
.race
.as_mut()
.and_then(|r| r.next_attempt(now))
else {
break;
};
if !self.address_allowed(addr, ice::AddressPurpose::StunTurnServer) {
debug!("TURN server {addr}: the address policy refuses it, not used");
if let Some(r) = self.streams.turn.links[index].race.as_mut() {
r.failed();
}
first_skipped = first;
continue;
}
if self.streams.turn.is_held_back(addr, now) {
debug!("TURN server {addr} is held back: not used");
if let Some(r) = self.streams.turn.links[index].race.as_mut() {
r.failed();
}
first_skipped = first;
continue;
}
if self
.streams
.turn
.is_refused(addr, &self.streams.turn.links[index].url)
{
debug!("TURN server {addr} refused this allocation for good: not asked again");
if let Some(r) = self.streams.turn.links[index].race.as_mut() {
r.failed();
}
first_skipped = first;
continue;
}
if first {
self.streams.srflx.transaction_started(now);
}
first_skipped = false;
if self.streams.turn.links[index].carrier == Carrier::Udp {
if !self.start_udp_attempt(now, index, addr)
&& let Some(r) = self.streams.turn.links[index].race.as_mut()
{
r.failed();
}
if self.streams.turn.links[index].state == LinkState::Failed {
break;
}
continue;
}
if self.streams.turn.links[index].carrier == Carrier::Dtls {
if !self.start_dtls_attempt(now, index, addr)
&& let Some(r) = self.streams.turn.links[index].race.as_mut()
{
r.failed();
}
if self.streams.turn.links[index].state == LinkState::Failed {
break;
}
continue;
}
let tls = self.streams.turn.links[index].tls();
let layer: Option<Box<dyn StreamLayer>> = if tls {
let Some(config) = self.streams.turn.tls_config.clone() else {
debug!("turns: server without roots or a verifier to check it: not used");
self.streams.turn.links[index].state = LinkState::Failed;
break;
};
match TlsLayer::new(config, self.streams.turn.links[index].certificate_name()) {
Ok(layer) => Some(Box::new(layer)),
Err(err) => {
debug!("TURN TLS: {err}");
self.streams.turn.links[index].state = LinkState::Failed;
break;
}
}
} else {
None
};
match self.streams.table.connect(
any_of_family(addr),
addr,
Framing::Turn,
TURN,
false,
layer,
) {
Ok(id) => self.streams.turn.links[index].attempts.push(id),
Err(_) => {
if let Some(r) = self.streams.turn.links[index].race.as_mut() {
r.failed();
}
}
}
}
if self.streams.turn.links[index]
.race
.as_ref()
.is_some_and(HappyEyeballs::exhausted)
{
// RFC 5928 section 3: the next SRV target, when there is one.
if let Some(next) = self.streams.turn.links[index]
.discovery
.as_mut()
.map(|d| d.next_target())
{
self.turn_discovery_next(index, next, now);
} else {
debug!(
"TURN server {}: no address connected",
self.streams.turn.links[index].url
);
self.streams.turn.links[index].state = LinkState::Failed;
// W3C webrtc-pc 4.8.3: "If no host candidate can reach the server,
// errorCode will be set to the value 701".
let l = &self.streams.turn.links[index];
let (transport, url) = (l.transport, l.url_string());
self.report_engine_gathering_error(
transport,
None,
url,
crate::peer_connection::event::ICE_SERVER_UNREACHABLE,
"no address of the server answered".to_owned(),
);
}
}
}
}
/// Acts on the next step of a link's discovery.
fn turn_discovery_next(
&mut self,
index: usize,
next: crate::peer_connection::dns_discovery::Next,
now: Instant,
) {
use crate::peer_connection::dns_discovery::Next;
match next {
Next::Records { name, kind } => {
let query = self.streams.table.resolve_records(name, kind);
let link = &mut self.streams.turn.links[index];
link.state = LinkState::Discovering(query);
if let Some(d) = link.discovery.as_mut() {
d.asked(query, now);
}
}
Next::Address { host, port } => match host.parse::<IpAddr>() {
Ok(ip) => {
let link = &mut self.streams.turn.links[index];
link.race = Some(HappyEyeballs::new(
vec![SocketAddr::new(ip, port)],
CONNECTION_ATTEMPT_DELAY,
));
link.state = LinkState::Connecting;
}
Err(_) => {
let query = self.streams.table.resolve(host, port);
let link = &mut self.streams.turn.links[index];
link.state = LinkState::Resolving(query);
link.query = Some(query);
link.race = None;
}
},
Next::Exhausted => {
debug!(
"TURN server {}: no target connected",
self.streams.turn.links[index].url
);
self.streams.turn.links[index].state = LinkState::Failed;
}
}
}
/// The NAPTR or SRV records the driver looked up for a link (`None`: the query timed out).
/// Returns whether the query was a link's.
pub(crate) fn turn_records(
&mut self,
query: u64,
records: &[shared::stream::DnsRecord],
) -> bool {
let now = self.pipeline_context.now;
let Some(index) = self
.streams
.turn
.links
.iter()
.position(|l| l.state == LinkState::Discovering(query))
else {
return false;
};
let Some(next) = self.streams.turn.links[index]
.discovery
.as_mut()
.map(|d| d.on_records(records))
else {
return false;
};
self.turn_discovery_next(index, next, now);
self.drive_turn_races(now);
true
}
/// A name the driver resolved: every address at once (`ipv6` `None`), or one family's
/// as it arrived (RFC 8305 section 3: the race starts on the first answer, and a late one
/// joins it).
pub(crate) fn turn_resolved(
&mut self,
query: u64,
ipv6: Option<bool>,
addresses: &[SocketAddr],
) {
let now = self.pipeline_context.now;
if let Some(index) = self.streams.turn.links.iter().position(|l| {
l.query == Some(query)
&& (l.state == LinkState::Resolving(query)
|| (l.state == LinkState::Connecting
&& l.race.as_ref().is_some_and(HappyEyeballs::awaiting)))
}) {
let ranks = self.turn_address_ranks(index, addresses);
let rank = |a: &SocketAddr| {
ranks
.iter()
.find(|(r, _)| r == a)
.map_or_else(AddressRank::default, |(_, rank)| *rank)
};
let link = &mut self.streams.turn.links[index];
match ipv6 {
None => {
link.query = None;
// No address: an exhausted race, which moves on to the next SRV target
// or fails the link (`drive_turn_races`).
let sorted = sort_addresses_ranked(addresses, true, rank);
link.race = Some(HappyEyeballs::new(sorted, CONNECTION_ATTEMPT_DELAY));
link.state = LinkState::Connecting;
}
Some(ipv6) => {
link.race
.get_or_insert_with(|| {
HappyEyeballs::awaiting_answers(CONNECTION_ATTEMPT_DELAY)
})
.answer_ranked(now, ipv6, addresses, true, rank);
link.state = LinkState::Connecting;
}
}
}
self.drive_turn_races(now);
}
/// RFC 8305 section 4: the history's rank of each of `addresses` for link `index`, from
/// the UDP base an attempt on that address would leave from. A link over TCP or TLS keeps
/// the resolver's order: the interface of its connection is the operating system's choice,
/// unknown before it connects, and the history "MUST NOT be used across different network
/// interfaces".
fn turn_address_ranks(
&self,
index: usize,
addresses: &[SocketAddr],
) -> Vec<(SocketAddr, AddressRank)> {
let link = &self.streams.turn.links[index];
if !link.on_datagrams() {
return vec![];
}
let transport = link.transport;
addresses
.iter()
.filter_map(|a| {
let base = self.turn_udp_base(transport, *a)?;
Some((*a, self.streams.history.rank(base.ip(), *a)))
})
.collect()
}
/// The time from the start of the attempt on `remote` of link `index` to now.
fn turn_attempt_rtt(&self, index: usize, remote: SocketAddr, now: Instant) -> Duration {
self.streams.turn.links[index]
.race
.as_ref()
.and_then(|r| r.started_at(remote))
.map_or(Duration::ZERO, |at| now.saturating_duration_since(at))
}
/// A TURN connection attempt connected: the race is won, the client starts.
pub(crate) fn turn_connected(
&mut self,
now: Instant,
id: StreamId,
local: SocketAddr,
remote: SocketAddr,
) {
let Some(index) = self.streams.turn.link_of_stream(id) else {
return;
};
if self.streams.turn.links[index].state != LinkState::Connecting {
return;
}
let losers: Vec<StreamId> = self.streams.turn.links[index]
.attempts
.iter()
.copied()
.filter(|a| *a != id)
.collect();
for loser in losers {
self.streams.table.reset(loser);
}
let Some(provider) = self.setting_engine.crypto_provider.clone() else {
self.streams.turn.links[index].state = LinkState::Failed;
return;
};
let options = self
.streams
.turn
.allocate_options(self.streams.turn.links[index].transport);
let link = &mut self.streams.turn.links[index];
if let Some(race) = link.race.as_mut() {
race.succeeded();
}
link.attempts = vec![id];
link.state = LinkState::Open(id);
link.server = Some(remote);
link.link_local = Some(local);
let config = turn::client::ClientConfig {
stun_serv_addr: remote.to_string(),
turn_serv_addr: remote.to_string(),
local_addr: local,
transport_protocol: TransportProtocol::TCP,
username: link.url.username.clone(),
password: link.url.password.clone(),
realm: String::new(),
rto_in_ms: 0,
allocation_refresh_interval_cap: self
.setting_engine
.turn_allocation_refresh_interval_cap,
software: self.setting_engine.turn_software(),
// RFC 8656 section 21.1.6: over TCP, not over TLS.
username_anonymity_required: self.setting_engine.turn_username_identifies_user
&& !link.tls(),
..Default::default()
};
let tcp = link.relay_tcp;
let resends = self.setting_engine.stun_server_error_resends;
let unauthenticated = self.setting_engine.turn_unauthenticated_allocations;
let engine_turn = &self.streams.turn;
let made = turn::client::Client::new(config, provider).and_then(|mut client| {
client.set_server_error_resends(resends);
client.set_unauthenticated_allocations(unauthenticated);
engine_turn.seed_turn_client(&mut client);
if tcp {
// RFC 6062 section 4.1: REQUESTED-TRANSPORT TCP.
client.allocate_with(now, tcp_relay::tcp_allocation())?;
} else {
client.allocate_with(now, options)?;
}
Ok(client)
});
let link = &mut self.streams.turn.links[index];
match made {
Ok(client) => link.client = Some(client),
Err(err) => {
debug!("TURN client for {}: {err}", link.url);
link.state = LinkState::Failed;
}
}
self.pump_turn(now);
}
/// A TURN connection attempt failed, or a TURN connection ended.
pub(crate) fn turn_connection_ended(&mut self, now: Instant, id: StreamId) {
let Some(index) = self.streams.turn.link_of_stream(id) else {
return;
};
let link = &mut self.streams.turn.links[index];
link.attempts.retain(|a| *a != id);
match link.state {
LinkState::Connecting => {
if let Some(race) = link.race.as_mut() {
race.failed();
}
self.drive_turn_races(now);
}
LinkState::Open(open) if open == id => {
// RFC 8656 section 3.1: the allocation lives as long as its connection.
debug!(
"TURN connection to {} ended: its allocation is gone",
link.url
);
self.turn_allocation_lost(now, index);
}
_ => {}
}
}
/// A link's allocation is gone with its connection (or DTLS association). RFC 6544 section
/// 11.2: when the session uses an address that server allocated, the client "SHOULD
/// reconnect to the TURN server, obtain a new allocation, and restart ICE": the link starts
/// over and ICE is restarted (`restart_ice`: the next offer has new credentials, and the
/// new generation announces the new relayed candidate). A link whose candidate is not in
/// use has failed.
pub(crate) fn turn_allocation_lost(&mut self, now: Instant, index: usize) {
let in_use = self.relay_in_use(index);
// The relayed candidates of the lost allocation leave the agent (they are not carried
// into the restart's session), and what the agent still writes from them goes nowhere.
let (transport, tcp) = {
let l = &self.streams.turn.links[index];
(l.transport, l.relay_tcp)
};
let gone: Vec<SocketAddr> = self.streams.turn.links[index].relays().collect();
for relay in gone {
self.withdraw_relay_candidate(transport, relay, tcp);
if !tcp {
self.streams.turn.dead_relays.insert(relay);
}
}
let link = &mut self.streams.turn.links[index];
// The client of a UDP link may still be deleting the allocation (a Refresh of
// LIFETIME 0 after a 400 to a ChannelBind, RFC 8656 section 12.3): it finishes as a
// release.
if link.carrier == Carrier::Udp
&& let (Some(base), Some(server)) = (link.link_local, link.server)
&& link
.client
.as_mut()
.is_some_and(|c| c.poll_timeout().is_some())
&& let Some(client) = link.client.take()
{
let url = link.url_string();
self.streams.turn.releases.push(UdpRelease {
url,
base,
server,
client,
relay: None,
signed: true,
done: false,
});
}
let link = &mut self.streams.turn.links[index];
for conn in std::mem::take(&mut link.data) {
if let Some(id) = conn.stream() {
self.streams.table.close(id);
}
}
let link = &mut self.streams.turn.links[index];
link.client = None;
link.relay = None;
link.relay_more.clear();
link.dtls = None;
link.udp_attempts.clear();
link.permitted.clear();
link.attempts.clear();
if in_use {
debug!(
"{}: reconnecting for a new allocation; ICE restarts",
link.url
);
link.state = LinkState::Pending;
link.race = None;
link.query = None;
link.discovery = None;
link.announced_ufrag = None;
self.restart_ice();
self.start_turn_links();
} else {
link.state = LinkState::Failed;
}
let _ = now;
}
/// An Allocate of link `index` was refused (RFC 8656 section 7.4). A 300 (Try Alternate)
/// is followed: the ALTERNATE-SERVER is tried before any other (7.4-3). A 486 or 508 holds
/// the server back for a minute, a 437 for two (RFC 5928 section 3: also against later
/// resolutions). Any refusal is the failure of that server: the resolution goes on with
/// its next SRV target, and when there is none the link has failed until a new ICE
/// generation restarts the resolution.
fn turn_allocate_refused(
&mut self,
now: Instant,
index: usize,
err: turn::client::RequestError,
) {
use stun::error_code::ErrorCode;
let link = &mut self.streams.turn.links[index];
let server = link.server;
let base = link.link_local;
let code = err.code();
let (url, carrier, transport) = (link.url_string(), link.carrier, link.transport);
if let Some(ErrorCode(c)) = code {
self.pipeline_context.event_outs.push_back(
crate::peer_connection::event::RTCPeerConnectionEvent::OnTurnRequestRejected {
url: url.clone(),
relay: None,
method: "Allocate",
error_code: c,
},
);
// W3C webrtc-pc 4.8.3: gathering from the server failed with its error code.
let reason = match &err {
turn::client::RequestError::Rejected(r) => r.reason.clone(),
other => format!("{other:?}"),
};
self.report_engine_gathering_error(transport, base, url, c, reason);
}
// RFC 8656 section 7.4, 437: "The client SHOULD pick another client transport address
// and retry the Allocate request [...] The client SHOULD try three different client
// transport addresses before giving up on this server." Over UDP the engine has the
// application's sockets only: another UDP base of the transport, if there is one.
if code == Some(ErrorCode(437))
&& carrier == Carrier::Udp
&& let (Some(base), Some(server)) = (base, server)
{
self.streams
.turn
.mismatched
.retain(|(_, _, until)| now < *until);
self.streams
.turn
.mismatched
.push((base, server, now + Duration::from_secs(120)));
let tried = self
.streams
.turn
.mismatched
.iter()
.filter(|(_, s, _)| *s == server)
.count();
let other = self
.streams
.turn
.udp_base(transport, server, |b| {
self.turn_base_usable(transport, b)
&& !self.streams.turn.is_mismatched(b, server, now)
})
.is_some();
if other && tried < 3 {
debug!("{server}: 437 on {base}; allocating from another base");
let link = &mut self.streams.turn.links[index];
link.client = None;
link.server = None;
link.link_local = None;
link.race = Some(HappyEyeballs::new(vec![server], CONNECTION_ATTEMPT_DELAY));
link.state = LinkState::Connecting;
self.drive_turn_races(now);
return;
}
}
// RFC 8656 section 7.4: after a 400, 403, 441 or 442 "the client SHOULD NOT retry the
// request with this server until it believes the problem has been fixed"; after a 401
// to the credentials "the client SHOULD NOT send any further requests to this server
// until it believes the problem has been fixed"; after a 440 "the client MUST NOT
// retry"; and section 7.3, after an allocation of a family it did not ask for, "the
// client MUST NOT ... retry" on that server "until it believes the mismatch has been
// fixed". The client that saw it is dropped below and a later ICE generation makes a
// new one, so the engine remembers the server itself.
let link = &self.streams.turn.links[index];
let of_credentials = matches!(code, Some(ErrorCode(401)) | Some(ErrorCode(441)));
let for_good = of_credentials
|| matches!(
code,
Some(ErrorCode(400))
| Some(ErrorCode(403))
| Some(ErrorCode(440))
| Some(ErrorCode(442))
)
|| link
.client
.as_ref()
.is_some_and(turn::client::Client::answered_another_family);
if for_good && let Some(server) = server {
debug!("TURN server {server} refused the allocation ({code:?}): not asked again");
let (username, password) = (link.url.username.clone(), link.url.password.clone());
self.streams.turn.refused.push(TurnRefusal {
server,
username,
password,
of_credentials,
});
}
// RFC 8656 section 7.3: an allocation the client cannot use is deleted with a Refresh
// of LIFETIME 0, which the client sent; over UDP it is a transaction with
// retransmissions, followed to its end as a release (`UdpRelease`) rather than dropped
// with the client.
let link = &mut self.streams.turn.links[index];
if link.carrier == Carrier::Udp
&& code.is_none()
&& let (Some(base), Some(server)) = (link.link_local, server)
&& let Some(mut client) = link.client.take()
{
if client.poll_timeout().is_some() {
let url = link.url_string();
self.streams.turn.releases.push(UdpRelease {
url,
base,
server,
client,
relay: None,
signed: true,
done: false,
});
} else {
link.client = Some(client);
}
}
// The connection (or association) to the refusing server is of no further use.
let link = &mut self.streams.turn.links[index];
if let LinkState::Open(id) = link.state {
self.streams.table.close(id);
}
let link = &mut self.streams.turn.links[index];
if let Some(mut dtls) = link.dtls.take() {
let r = dtls.remote;
let _ = dtls.endpoint.stop(now, r);
dtls.flush(&mut self.pipeline_context.write_outs);
}
let link = &mut self.streams.turn.links[index];
link.client = None;
link.attempts.clear();
for conn in std::mem::take(&mut link.data) {
if let Some(id) = conn.stream() {
self.streams.table.close(id);
}
}
let hold = match code {
Some(ErrorCode(486)) | Some(ErrorCode(508)) => Some(Duration::from_secs(60)),
Some(ErrorCode(437)) => Some(Duration::from_secs(120)),
_ => None,
};
if matches!(code, Some(ErrorCode(486)) | Some(ErrorCode(508)))
&& carrier == Carrier::Udp
&& let (Some(base), Some(server)) = (base, server)
{
self.fall_back_to_binding(now, transport, base, server);
}
if let (Some(hold), Some(server)) = (hold, server) {
debug!("TURN server {server} held back for {hold:?}");
self.streams
.turn
.held_back
.retain(|(a, until)| *a != server && now < *until);
self.streams.turn.held_back.push((server, now + hold));
}
let link = &mut self.streams.turn.links[index];
// RFC 8489 section 14.15: the ALTERNATE-SERVER names "a different STUN server"; one
// that can be none (port 0, an unspecified, multicast, broadcast or IPv4-mapped
// address, a loopback address from a server elsewhere) is not followed, and the link
// goes on as after any other refusal.
let original = server
.map(|s| s.ip())
.unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED));
// RFC 8489 section 10: "If the client has been redirected to a server to which it has
// already sent this request within the last five minutes, it MUST ignore the
// redirection and consider the transaction to have failed."
if code == Some(ErrorCode(300))
&& let Some(server) = server
{
link.redirect_guard.sent_to(server, now);
}
if code == Some(ErrorCode(300))
&& link.redirects < MAX_REDIRECTS
&& let turn::client::RequestError::Rejected(response) = &err
&& let Some(alternate) = response.alternate_server
&& stun::alternate::is_usable_alternate(alternate, original)
&& link.redirect_guard.follow(alternate, now)
{
debug!("{}: trying the alternate server {alternate}", link.url);
link.redirects += 1;
// RFC 8489 section 10: over TLS or DTLS, "If the attribute is found, the domain
// MUST be used to validate the certificate ... If the attribute is not found, the
// same domain that was used for the original request MUST be used." Only an
// authenticated 300 gives one (`try_alternate`, section 14.8).
if let Some(domain) = response
.try_alternate
.as_ref()
.and_then(|t| t.domain.clone())
{
link.alternate_domain = Some(domain);
}
link.race = Some(HappyEyeballs::new(
vec![alternate],
CONNECTION_ATTEMPT_DELAY,
));
link.state = LinkState::Connecting;
self.drive_turn_races(now);
return;
}
if let Some(next) = link.discovery.as_mut().map(|d| d.next_target()) {
link.state = LinkState::Connecting;
self.turn_discovery_next(index, next, now);
self.drive_turn_races(now);
} else {
link.state = LinkState::Failed;
}
}
/// Whether the selected pair of the link's transport has its relayed candidate as the
/// local one.
fn relay_in_use(&self, index: usize) -> bool {
let link = &self.streams.turn.links[index];
let Some(relay) = link.relay else {
return false;
};
self.ice_transport_of(link.transport)
.agent
.get_selected_candidate_pair()
.is_some_and(|(local, _)| {
let addr = local.addr();
link.is_relay(addr)
|| (link.relay_tcp && addr.ip() == relay.ip() && addr.port() == 9)
})
}
/// RFC 6544 section 11.2: once ICE of a transport has completed, the connection to a TURN
/// server whose relayed candidate the selected pair does not use is closed (it "MUST be
/// kept open ... if a relayed candidate from the TURN server was selected"). Its
/// allocation goes with it; a later ICE generation allocates again.
pub(crate) fn close_settled_turn_links(&mut self) {
for index in 0..self.streams.turn.links.len() {
let link = &self.streams.turn.links[index];
let LinkState::Open(id) = link.state else {
continue;
};
if link.retiring {
continue;
}
let transport = link.transport;
// RFC 8445 section 8.3.1: three seconds after the pair was selected.
let completed = self.ice_settled(transport);
let link = &self.streams.turn.links[index];
if !completed || link.relay.is_none() || self.relay_in_use(index) {
continue;
}
// webrtc-extensions 7: freeing the relayed candidate removes its pairs first, as a
// cancelable proposal under `with_candidate_pair_proposals` (`pair_removal`); a
// cancelled one keeps the link.
let (transport, relay, relay_tcp) = (link.transport, link.relay, link.relay_tcp);
let carries = |local: &ice::candidate::Candidate, _: &ice::candidate::Candidate| {
relay.is_some_and(|relay| {
let addr = local.addr();
addr == relay || (relay_tcp && addr.ip() == relay.ip() && addr.port() == 9)
})
};
if !self.remove_freed_pairs(transport, carries) {
continue;
}
let link = &self.streams.turn.links[index];
debug!(
"{}: ICE completed without its relayed candidate: closed",
link.url
);
let link = &mut self.streams.turn.links[index];
for conn in std::mem::take(&mut link.data) {
if let Some(id) = conn.stream() {
self.streams.table.close(id);
}
}
let link = &mut self.streams.turn.links[index];
link.state = LinkState::Released;
link.client = None;
link.relay = None;
link.relay_more.clear();
link.attempts.clear();
link.permitted.clear();
self.streams.table.close(id);
}
}
/// TURN messages read from a link.
pub(crate) fn turn_messages(&mut self, now: Instant, id: StreamId, messages: Vec<Vec<u8>>) {
let Some(index) = self.streams.turn.link_of_stream(id) else {
return;
};
let link = &mut self.streams.turn.links[index];
let (Some(server), Some(local)) = (link.server, link.link_local) else {
return;
};
if let Some(client) = link.client.as_mut() {
for message in messages {
if let Err(err) = client.handle_read(TaggedBytesMut {
now,
transport: tcp_context(local, server),
message: BytesMut::from(&message[..]),
}) {
debug!("TURN message from {server}: {err}");
}
}
}
self.pump_turn(now);
}
/// Moves what the TURN clients have to send onto their connections and acts on their
/// events.
pub(crate) fn pump_turn(&mut self, now: Instant) {
self.pump_udp_attempts(now);
let mut inbound = vec![];
let mut announce = vec![];
let mut peers_ready = vec![];
let mut failed_peers = vec![];
let mut refused = vec![];
let mut lost: Vec<usize> = vec![];
let mut rejected = vec![];
let mut accepted = vec![];
for index in 0..self.streams.turn.links.len() {
let link = &mut self.streams.turn.links[index];
let id = match link.state {
LinkState::Open(id) => Some(id),
LinkState::OpenDtls | LinkState::OpenUdp => None,
_ => continue,
};
let link_url = link.url_string();
let Some(client) = link.client.as_mut() else {
continue;
};
let mut granted = vec![];
let mut bind_failed: Vec<SocketAddr> = vec![];
while let Some(event) = client.poll_event() {
match event {
turn::client::Event::AllocateResponse(_, relayed) => {
link.relay = Some(relayed);
announce.push(index);
// RFC 8489 section 9.2.3.2: what the server accepted is cached for
// the connection's later allocations to it.
if let Some(cached) = client.cached_credential() {
accepted.push(cached);
}
}
turn::client::Event::AllocateError(_, err) => {
debug!("TURN allocation on {} refused: {err:?}", link.url);
refused.push((index, err));
}
// Before the allocation the only request out is the Allocate: one that
// timed out (a silent server, or one whose only answer was an unsigned
// 400, RFC 8489 section 9.2.5) is that server's failure, as a refusal is.
turn::client::Event::TransactionTimeout(_) if link.relay.is_none() => {
debug!("TURN allocation on {} timed out", link.url);
refused.push((
index,
turn::client::RequestError::Failed(shared::error::Error::ErrTimeout),
));
}
turn::client::Event::AllocationLost(_, err) => {
debug!("TURN allocation on {} lost: {err:?}", link.url);
rejected.push((link_url.clone(), link.relay, "Refresh", err.code()));
// RFC 8656 section 12.3 (a 400 to a ChannelBind: "delete the allocation
// and start afresh with a new allocation"), and any allocation lost:
// `turn_allocation_lost` starts the link over when its relayed
// candidate carries the session.
lost.push(index);
}
turn::client::Event::RefreshError(relay, err) => {
debug!("TURN Refresh on {} refused: {err:?}", link.url);
rejected.push((link_url.clone(), Some(relay), "Refresh", err.code()));
}
turn::client::Event::PermissionLost(relay, _, err) => {
rejected.push((
link_url.clone(),
Some(relay),
"CreatePermission",
err.code(),
));
}
turn::client::Event::ChannelBindError(relay, peer, err) => {
rejected.push((link_url.clone(), Some(relay), "ChannelBind", err.code()));
bind_failed.push(peer);
}
turn::client::Event::CreatePermissionResponse(_, peer) => {
granted.push(peer.ip());
}
turn::client::Event::CreatePermissionError(_, err) => {
debug!("TURN permission refused: {err:?}");
rejected.push((
link_url.clone(),
link.relay,
"CreatePermission",
err.code(),
));
}
turn::client::Event::DataIndicationOrChannelData(_, peer, data) => {
// On the relayed address of the peer's family.
let relay = link
.relay_more
.iter()
.copied()
.find(|r| r.is_ipv6() == peer.is_ipv6())
.or(link.relay);
if let Some(relay) = relay {
inbound.push((link.transport, relay, peer, data));
}
}
turn::client::Event::ConnectResponse(_, peer, connection_id) => {
peers_ready.push((index, peer, connection_id, false));
}
turn::client::Event::ConnectionAttempt(_, peer, connection_id) => {
peers_ready.push((index, peer, connection_id, true));
}
turn::client::Event::ConnectError(_, peer, err) => {
debug!("TURN Connect to {peer}: {err:?}");
failed_peers.push((index, peer));
}
_ => {}
}
}
// A dual allocation (`EngineTurn::allocate_options`): its second relayed address.
if announce.last() == Some(&index)
&& let (Some(relay), Some(client)) = (link.relay, link.client.as_mut())
&& let Ok(r) = client.relay(relay)
{
link.relay_more = r
.relayed_addrs()
.into_iter()
.filter(|a| *a != relay)
.collect();
}
// Data held for its channel: as ChannelData once the channel is bound; as Send
// indications when the server refused the channel (RFC 8656 section 12: a channel
// is optional).
if let (Some(relay), Some(client)) = (link.relay, link.client.as_mut())
&& !link.channel_held.is_empty()
{
for (peer, data) in std::mem::take(&mut link.channel_held) {
let Ok(mut r) = client.relay(relay) else {
continue;
};
if r.channel_ready(now, peer) {
let _ = r.send_to(now, &data, peer);
} else if bind_failed.contains(&peer) {
let _ = r.send_indication_to(now, &data, peer);
} else {
link.channel_held.push((peer, data));
}
}
}
if let (Some(relay), Some(client)) = (link.relay, link.client.as_mut()) {
for ip in granted {
for (peer, data) in link.held.remove(&ip).unwrap_or_default() {
// Held for the permission: sent before a pair through the relay
// can be selected, so as a Send indication (`turn_channel_wanted`).
if let Ok(mut r) = client.relay(relay) {
let _ = r.send_indication_to(now, &data, peer);
}
}
}
}
if let Some(client) = link.client.as_mut() {
while let Some(transmit) = client.poll_write() {
match (id, link.dtls.as_mut()) {
(Some(id), _) => {
let _ = self.streams.table.send(id, &transmit.message);
}
(None, Some(dtls)) => {
let remote = dtls.remote;
if let Err(err) = dtls.endpoint.write(now, remote, &transmit.message) {
debug!("TURN over DTLS to {remote}: {err}");
}
dtls.flush(&mut self.pipeline_context.write_outs);
}
(None, None) if link.carrier == Carrier::Udp => {
if let (Some(base), Some(server)) = (link.link_local, link.server) {
self.pipeline_context.write_outs.push_back(TaggedBytesMut {
now,
transport: udp_context(base, server),
message: transmit.message,
});
}
}
(None, None) => {}
}
}
}
}
for cached in accepted {
self.streams.turn.remember_turn_credential(cached);
}
let announced = !announce.is_empty();
for index in announce {
self.announce_relay_candidate(index);
}
// A link waiting for its server's first allocation (`extra_base`) can go on.
if announced {
self.drive_turn_races(now);
}
for (index, peer, connection_id, attempt) in peers_ready {
self.turn_tcp_peer_ready(index, peer, connection_id, attempt);
}
for (index, peer) in failed_peers {
self.turn_tcp_connect_failed(now, index, peer);
}
// A request the server finally refused (the client retried a 401 / 438 already):
// the application hears of it, a REST credential that expired, say.
for (url, relay, method, code) in rejected {
if let Some(code) = code {
self.pipeline_context.event_outs.push_back(
crate::peer_connection::event::RTCPeerConnectionEvent::OnTurnRequestRejected {
url,
relay,
method,
error_code: code.0,
},
);
}
}
for (index, err) in refused {
self.turn_allocate_refused(now, index, err);
}
for index in lost {
// The control connection, still open, is of no further use.
if let LinkState::Open(id) = self.streams.turn.links[index].state {
self.streams.table.close(id);
}
self.turn_allocation_lost(now, index);
}
for index in 0..self.streams.turn.links.len() {
self.pump_turn_data(now, index);
}
for (transport, relay, peer, data) in inbound {
// On the transport the relayed candidate is of.
self.pipeline_context.observe(now);
self.read_on_transport(
transport,
TaggedBytesMut {
now,
transport: TransportContext {
local_addr: relay,
peer_addr: peer,
transport_protocol: TransportProtocol::UDP,
ecn: None,
},
message: data,
},
);
}
self.finish_deferred_gathering();
}
fn announce_relay_candidate(&mut self, index: usize) {
let link = &self.streams.turn.links[index];
let (Some(relay), Some(local)) = (link.relay, link.link_local) else {
return;
};
let (url, protocol, transport) = (link.url_string(), link.protocol(), link.transport);
if !link.relay_tcp {
let relays: Vec<SocketAddr> = link.relays().collect();
for r in relays {
self.streams.turn.dead_relays.remove(&r);
}
}
let link = &self.streams.turn.links[index];
// A TCP allocation: a passive relayed candidate, and on port 9 an active one (RFC
// 6544 sections 4.5 and 5.5). A UDP allocation: one per relayed address (two of a dual
// allocation, `EngineTurn::allocate_options`).
let kinds: Vec<(IpAddr, &str, u16, Option<ice::tcp_type::TcpType>)> = if link.relay_tcp {
vec![
(
relay.ip(),
"tcp",
relay.port(),
Some(ice::tcp_type::TcpType::Passive),
),
(relay.ip(), "tcp", 9, Some(ice::tcp_type::TcpType::Active)),
]
} else {
link.relays()
.map(|r| (r.ip(), "udp", r.port(), None))
.collect()
};
for (ip, network, port, tcp_type) in kinds {
let candidate = ice::candidate::candidate_relay::CandidateRelayConfig {
base_config: ice::candidate::CandidateConfig {
network: network.to_owned(),
address: ip.to_string(),
port,
component: 1,
..Default::default()
},
rel_addr: local.ip().to_string(),
rel_port: local.port(),
..Default::default()
}
.new_candidate_relay()
.and_then(|mut c| {
if let Some(tcp_type) = tcp_type {
c.set_tcp_type(tcp_type);
}
crate::peer_connection::transport::RTCIceCandidate::from(&c).to_json()
});
match candidate {
Ok(init) => {
let value = init
.candidate
.strip_prefix("candidate:")
.unwrap_or(&init.candidate)
.to_owned();
if let Err(err) = self.add_engine_local_candidate(
transport,
&value,
Some(&url),
Some(protocol),
) {
debug!("relayed candidate {relay} not added: {err}");
}
let ufrag = self
.ice_transport_of(transport)
.agent
.get_local_credentials()
.ufrag
.clone();
self.streams.turn.links[index].announced_ufrag = Some(ufrag);
}
Err(err) => debug!("relayed candidate {relay} not made: {err}"),
}
}
}
/// Sends a datagram the agent wrote from a relayed candidate through its TURN link: at
/// once with a permission for the peer, else after one is created (RFC 8656 section 9).
pub(crate) fn send_via_turn(&mut self, index: usize, msg: TaggedBytesMut) {
let now = msg.now.max(self.pipeline_context.now);
let peer = msg.transport.peer_addr;
let channel = self.turn_channel_wanted(index, peer);
let link = &mut self.streams.turn.links[index];
let (Some(relay), Some(client)) = (link.relay, link.client.as_mut()) else {
return;
};
let Ok(mut r) = client.relay(relay) else {
return;
};
// Data, not a STUN check (RFC 7983: 0 to 3), for a peer whose channel is not bound yet.
let wait_for_channel =
channel && msg.message.first().is_some_and(|b| *b > 3) && !r.channel_ready(now, peer);
let sent = if wait_for_channel {
r.bind_channel(now, peer)
} else if channel {
r.send_to(now, &msg.message, peer)
} else {
r.send_indication_to(now, &msg.message, peer)
};
if wait_for_channel && sent.is_ok() && link.channel_held.len() < MAX_HELD_FOR_CHANNEL {
link.channel_held.push((peer, msg.message.to_vec()));
}
match sent {
Ok(()) => {}
Err(shared::error::Error::ErrNoPermission) => {
let first = !link.held.contains_key(&peer.ip());
let held = link.held.entry(peer.ip()).or_default();
if held.len() < MAX_HELD_PER_PEER {
held.push((peer, msg.message.to_vec()));
}
if first && let Ok(mut r) = client.relay(relay) {
let _ = r.create_permission(now, peer);
}
}
Err(err) => debug!("TURN send to {peer}: {err}"),
}
self.pump_turn(now);
}
/// Whether what link `index` relays to `peer` may go on a TURN channel: only once ICE of
/// its transport has selected the pair from the link's relayed candidate to `peer`. RFC
/// 8445 section 7.2.1: "it is RECOMMENDED that the agent defer creation of a TURN channel
/// until ICE completes", and section 12.1 (RECOMMENDED) then binds one to the remote
/// candidate of the selected pair. Until then the checks, and anything else relayed, go
/// as Send indications, which need a permission only.
fn turn_channel_wanted(&self, index: usize, peer: SocketAddr) -> bool {
let link = &self.streams.turn.links[index];
if link.relay.is_none() {
return false;
}
self.ice_transport_of(link.transport)
.agent
.get_selected_candidate_pair()
.is_some_and(|(local, remote)| link.is_relay(local.addr()) && remote.addr() == peer)
}
/// A new DTLS association needs a new 3-tuple (RFC 8842 section 5.1), the relayed one
/// included: each link of the active transport that holds an allocation deletes it (over
/// UDP a Refresh of LIFETIME 0, RFC 8656 section 8; over TCP, TLS and DTLS its connection
/// closes) and starts over, so that the new ICE generation announces the relayed
/// candidate of a new allocation.
pub(crate) fn reallocate_turn_links_of_active_transport(&mut self, now: Instant) {
let transport = self.pipeline_context.transports.active_id();
// A local offer not answered yet may be rolled back, and "Any resources or candidates
// that were allocated by the abandoned local description are discarded" (RFC 9429
// section 5.7) while the session before it goes on: its allocations are kept,
// retiring, and new links allocate for the new generation (make before break, from
// the new bases the new association needs). The answer commits the restart and the
// retiring links are released once the data has left them
// (`release_retired_turn_links`); a rollback drops the new links and brings the old
// ones back (`revert_turn_generation`).
if self.restart_uncommitted(transport) {
let ufrag = self
.ice_transport_of(transport)
.agent
.get_local_credentials()
.ufrag
.clone();
let mut fresh = vec![];
for l in self
.streams
.turn
.links
.iter_mut()
.filter(|l| l.transport == transport && l.relay.is_some() && !l.retiring)
{
debug!(
"{}: a new DTLS association: kept retiring, allocating anew",
l.url
);
l.retiring = true;
l.retired_for = Some(ufrag.clone());
let mut link = TurnLink::pending(transport, l.url.clone(), l.carrier, l.relay_tcp);
link.created_for = Some(ufrag.clone());
fresh.push(link);
}
self.streams.turn.links.extend(fresh);
return;
}
let mut ended = vec![];
let out = &mut self.pipeline_context.write_outs;
let releases = &mut self.streams.turn.releases;
for l in self
.streams
.turn
.links
.iter_mut()
.filter(|l| l.transport == transport && l.relay.is_some())
{
ended.extend(
std::mem::take(&mut l.data)
.iter()
.filter_map(|c| c.stream()),
);
if let Some(a) = l.dtls.as_mut() {
let _ = a.endpoint.close(now);
a.flush(out);
}
release_udp_allocation(l, now, out, releases);
if let LinkState::Open(id) = l.state {
ended.push(id);
}
debug!("{}: a new DTLS association: allocating again", l.url);
l.client = None;
l.relay = None;
l.relay_more.clear();
l.dtls = None;
l.udp_attempts.clear();
l.permitted.clear();
l.attempts.clear();
l.state = LinkState::Pending;
l.race = None;
l.query = None;
l.discovery = None;
l.announced_ufrag = None;
}
for id in ended {
self.streams.table.close(id);
}
}
/// Closes links taken out of the engine (their server left the list a new generation
/// took): their connections end, a DTLS association says close_notify, an allocation
/// over UDP is deleted.
fn close_turn_links(&mut self, mut links: Vec<TurnLink>) {
let now = self.pipeline_context.now;
let out = &mut self.pipeline_context.write_outs;
let releases = &mut self.streams.turn.releases;
let mut ended = vec![];
for l in links.iter_mut() {
ended.extend(l.attempts.iter().copied());
ended.extend(l.data.iter().filter_map(|c| c.stream()));
for a in l.dtls.iter_mut().chain(l.dtls_attempts.iter_mut()) {
let _ = a.endpoint.close(now);
a.flush(out);
}
release_udp_allocation(l, now, out, releases);
}
for id in ended {
self.streams.table.close(id);
}
}
/// Releases every link of `on` (a Refresh of LIFETIME 0 over UDP, RFC 8656 section 7;
/// the connection's end otherwise) and forgets the servers its generation took: the
/// gathering of a rolled-back first local offer is discarded (RFC 9429 section 5.7), and
/// the next local description makes its links anew.
pub(crate) fn release_turn_links_of(&mut self, on: TransportId) {
let mut gone = vec![];
let mut i = 0;
while i < self.streams.turn.links.len() {
if self.streams.turn.links[i].transport == on {
gone.push(self.streams.turn.links.remove(i));
} else {
i += 1;
}
}
self.close_turn_links(gone);
self.streams.turn.made_for.remove(&on);
self.streams.turn.udp_bases.retain(|(t, _)| *t != on);
self.streams.turn.servers.forget(on);
}
/// Drops the links of transports a description removed, and their connections.
pub(crate) fn release_removed_turn_links(&mut self) {
let ids = self.pipeline_context.transports.ids();
let mut ended = vec![];
let now = self.pipeline_context.now;
let out = &mut self.pipeline_context.write_outs;
let releases = &mut self.streams.turn.releases;
self.streams.turn.links.retain_mut(|l| {
let kept = ids.contains(&l.transport);
if !kept {
ended.extend(l.attempts.iter().copied());
ended.extend(l.data.iter().filter_map(|c| c.stream()));
// A DTLS association says close_notify; an allocation over UDP is deleted.
for a in l.dtls.iter_mut().chain(l.dtls_attempts.iter_mut()) {
let _ = a.endpoint.close(now);
a.flush(out);
}
release_udp_allocation(l, now, out, releases);
}
kept
});
self.streams.turn.made_for.retain(|t| ids.contains(t));
self.streams.turn.servers.retain_transports(&ids);
self.streams.turn.udp_bases.retain(|(t, _)| ids.contains(t));
for id in ended {
self.streams.table.close(id);
}
}
/// The TURN clients' and races' next timer.
pub(crate) fn turn_poll_timeout(&mut self) -> Option<Instant> {
let now = self.pipeline_context.now;
// A first attempt held by the Ta gate is due when the gate opens.
let mut next: Option<Instant> = self.streams.srflx.ta_gate().filter(|gate| {
*gate > now
&& self.streams.turn.links.iter().any(|l| {
l.state == LinkState::Connecting
&& l.attempts.is_empty()
&& l.udp_attempts.is_empty()
&& l.dtls_attempts.is_empty()
&& l.client.is_none()
})
});
for link in self.streams.turn.links.iter_mut() {
let t = match link.state {
LinkState::Discovering(_) => link.discovery.as_ref().and_then(|d| d.poll_timeout()),
LinkState::Connecting => link
.race
.as_ref()
.and_then(HappyEyeballs::poll_timeout)
.into_iter()
.chain(
link.dtls_attempts
.iter()
.filter_map(|a| a.endpoint.poll_timeout(&a.remote)),
)
.chain(
link.udp_attempts
.iter_mut()
.filter_map(|a| a.client.poll_timeout()),
)
.min(),
LinkState::Open(_) | LinkState::OpenUdp => {
link.client.as_mut().and_then(|c| c.poll_timeout())
}
LinkState::OpenDtls => link
.client
.as_mut()
.and_then(|c| c.poll_timeout())
.into_iter()
.chain(
link.dtls
.as_ref()
.and_then(|a| a.endpoint.poll_timeout(&a.remote)),
)
.min(),
_ => None,
};
if let Some(t) = t {
next = Some(next.map_or(t, |n| n.min(t)));
}
}
if let Some(t) = self.turn_data_poll_timeout() {
next = Some(next.map_or(t, |n| n.min(t)));
}
if let Some(t) = self.turn_releases_poll_timeout() {
next = Some(next.map_or(t, |n| n.min(t)));
}
// The end of a reallocation delay an Allocate waits for.
let turn = &self.streams.turn;
let waits = |base: SocketAddr, server: SocketAddr| {
turn.links.iter().any(|l| {
l.udp_attempts
.iter()
.any(|a| !a.sent && a.base == base && a.remote == server)
})
};
if let Some(t) = turn
.freed
.iter()
.filter(|(b, s, _)| waits(*b, *s))
.map(|(_, _, at)| *at)
.min()
{
next = Some(next.map_or(t, |n| n.min(t)));
}
next
}
/// Fires the TURN clients' and races' timers.
pub(crate) fn turn_handle_timeout(&mut self, now: Instant) {
// A DTLS link whose base was added before the local description starts now.
self.start_turn_links();
self.turn_releases_handle_timeout(now);
self.start_waiting_udp_attempts(now);
if self.streams.turn.links.is_empty() {
return;
}
for link in self.streams.turn.links.iter_mut() {
if let (LinkState::Open(_) | LinkState::OpenDtls | LinkState::OpenUdp, Some(client)) =
(link.state, link.client.as_mut())
&& let Err(err) = client.handle_timeout(now)
{
debug!("TURN client timer: {err}");
}
for a in link.udp_attempts.iter_mut() {
if a.client.poll_timeout().is_some_and(|t| t <= now)
&& let Err(err) = a.client.handle_timeout(now)
{
debug!("TURN Allocate to {}: {err}", a.remote);
}
}
}
// An Allocate that lost its race and was never answered is forgotten.
self.streams.turn.udp_losers.retain_mut(|l| {
l.client
.poll_timeout()
.is_some_and(|t| t + LOSER_GRACE > now)
});
self.turn_dtls_timeouts(now);
self.turn_data_handle_timeout(now);
// A records query the driver did not answer counts as empty.
let unanswered: Vec<u64> = self
.streams
.turn
.links
.iter()
.filter_map(|l| match l.state {
LinkState::Discovering(q)
if l.discovery.as_ref().is_some_and(|d| d.timed_out(now)) =>
{
Some(q)
}
_ => None,
})
.collect();
for query in unanswered {
self.turn_records(query, &[]);
}
self.drive_turn_races(now);
self.pump_turn(now);
self.release_retired_turn_links();
}
/// Raises `icecandidateerror` (W3C webrtc-pc 4.8.3) for a server the engine gathers from
/// itself: `base`, the local address it used (left out when no candidate exposes it),
/// the server's URL, its STUN error code or 701.
pub(crate) fn report_engine_gathering_error(
&mut self,
transport: TransportId,
base: Option<SocketAddr>,
url: String,
error_code: u16,
error_text: String,
) {
let error = crate::peer_connection::event::RTCPeerConnectionIceErrorEvent {
address: base.map(|b| b.ip().to_string()).unwrap_or_default(),
port: base.map_or(0, |b| b.port()),
url,
error_code,
error_text,
ice_transport: Some(self.ice_transport_of(transport).id),
};
if let Err(err) = self.report_ice_candidate_error(error) {
debug!("icecandidateerror not raised: {err}");
}
}
/// Whether the relayed candidate of `link` is the local end of the path the agent of its
/// transport sends data on, or still takes data on (the path an ICE restart replaced, for
/// `RETIRED_MEDIA_PATH_GRACE` after the restart selected its pair).
/// Whether `transport` has an ICE restart a local offer applied and no answer has
/// committed yet: a rollback of the offer would take it back (RFC 9429 section 5.7).
fn restart_uncommitted(&self, transport: TransportId) -> bool {
self.ice_transport_of(transport)
.gathering_before_local_restart
.is_some()
}
/// RFC 9429 section 5.7: "Any resources or candidates that were allocated by the abandoned
/// local description are discarded". The local offer that began generation `abandoned` of
/// `transport` was rolled back and `restored` is its generation again. Its servers are the
/// ones `restored` took; the links that generation retired gather again for it as before;
/// the allocations made for the abandoned generation are released (a Refresh of LIFETIME
/// 0 over UDP, RFC 8656 section 7; the connection's end over TCP / TLS; close_notify over
/// DTLS): the links made for it, the links of a server the restored list does not take,
/// and a link that allocated again for it (one released once ICE had completed). Their
/// relayed candidates are not announced for the restored generation.
pub(crate) fn revert_turn_generation(
&mut self,
transport: TransportId,
abandoned: &str,
restored: &str,
) {
self.streams
.turn
.servers
.revert(transport, abandoned, restored);
let servers: Vec<Url> = self
.streams
.turn
.servers
.taken_by(transport)
.map(<[Url]>::to_vec)
.unwrap_or_default();
let mut dropped = vec![];
let mut again = vec![];
let mut i = 0;
while i < self.streams.turn.links.len() {
let l = &mut self.streams.turn.links[i];
if l.transport != transport {
i += 1;
continue;
}
if l.retiring {
if l.retired_for.as_deref() == Some(abandoned) {
l.retiring = false;
l.retired_for = None;
}
i += 1;
continue;
}
let made_for_abandoned = l.created_for.as_deref() == Some(abandoned);
let listed = servers.iter().any(|u| same_url(u, &l.url));
if made_for_abandoned || !listed {
dropped.push(self.streams.turn.links.remove(i));
continue;
}
if l.generation.as_deref() == Some(abandoned) {
again.push(i);
} else if l.announced_ufrag.as_deref() == Some(abandoned) {
// Announced again for the abandoned generation: the restored session holds
// the candidate already (`Agent::revert_restart`).
l.announced_ufrag = Some(restored.to_owned());
}
i += 1;
}
if !dropped.is_empty() {
debug!(
"{} TURN link(s) of a rolled-back ICE generation released",
dropped.len()
);
}
self.close_turn_links(dropped);
for i in again {
debug!(
"{}: allocated for a rolled-back ICE generation: released",
self.streams.turn.links[i].url
);
self.release_turn_link_in_place(i);
let l = &mut self.streams.turn.links[i];
// Released as it was for the restored generation; a later one allocates again.
l.announced_ufrag = Some(restored.to_owned());
l.generation = Some(restored.to_owned());
}
}
fn turn_relay_carries_data(&self, link: &TurnLink) -> bool {
let Some(relay) = link.relay else {
return false;
};
let agent = &self.ice_transport_of(link.transport).agent;
[agent.media_path(), agent.retired_media_path()]
.into_iter()
.flatten()
.any(|p| {
link.is_relay(p.local_addr)
|| (link.relay_tcp
&& p.local_addr.ip() == relay.ip()
&& p.local_addr.port() == 9)
})
}
/// Withdraws the relayed candidate(s) of `relay` from the agent of `transport` (UDP, or
/// the passive and active TCP candidates of a TCP allocation).
fn withdraw_relay_candidate(&mut self, transport: TransportId, relay: SocketAddr, tcp: bool) {
let now = self.pipeline_context.now;
let targets: Vec<(SocketAddr, TransportProtocol)> = if tcp {
vec![
(relay, TransportProtocol::TCP),
(SocketAddr::new(relay.ip(), 9), TransportProtocol::TCP),
]
} else {
vec![(relay, TransportProtocol::UDP)]
};
self.with_transport(transport, |pc| {
for (addr, protocol) in targets {
pc.ice_transport_mut()
.agent
.withdraw_local_candidate(now, addr, protocol);
}
});
}
/// Releases the retiring links whose relayed candidate no longer carries data (the
/// restart's pair is selected and the previous path's grace is over) or whose allocation is
/// gone: an allocation over UDP is deleted with a Refresh of LIFETIME 0 (RFC 8656 section
/// 7), a DTLS association says close_notify, a connection closes. The links are dropped.
pub(crate) fn release_retired_turn_links(&mut self) {
for i in 0..self.streams.turn.links.len() {
let link = &self.streams.turn.links[i];
if link.retiring
&& link.client.is_some()
&& link.state != LinkState::Failed
&& !self.turn_relay_carries_data(link)
&& !self.restart_uncommitted(link.transport)
{
debug!(
"{}: the data left its relayed candidate: released",
link.url
);
self.release_turn_link_in_place(i);
}
}
self.streams
.turn
.links
.retain(|l| !(l.retiring && (l.client.is_none() || l.state == LinkState::Failed)));
}
/// Releases link `i` where it is (its index stays valid): its connections end, a DTLS
/// association says close_notify, an allocation over UDP is deleted with a Refresh of
/// LIFETIME 0; it holds no client or relayed address afterwards.
fn release_turn_link_in_place(&mut self, i: usize) {
let now = self.pipeline_context.now;
let out = &mut self.pipeline_context.write_outs;
let link = &mut self.streams.turn.links[i];
let mut ended: Vec<StreamId> = std::mem::take(&mut link.attempts);
ended.extend(
std::mem::take(&mut link.data)
.iter()
.filter_map(|c| c.stream()),
);
if let LinkState::Open(id) = link.state {
ended.push(id);
}
for a in link.dtls.iter_mut().chain(link.dtls_attempts.iter_mut()) {
let _ = a.endpoint.close(now);
a.flush(out);
}
release_udp_allocation(link, now, out, &mut self.streams.turn.releases);
link.client = None;
link.relay = None;
link.relay_more.clear();
link.dtls = None;
link.dtls_attempts.clear();
link.udp_attempts.clear();
link.permitted.clear();
link.held.clear();
link.state = LinkState::Released;
for id in ended {
self.streams.table.close(id);
}
}
/// The UDP base of `transport` a new link to `server` starts from: one no other link holds
/// an allocation or a DTLS association from to that address, since an allocation is its
/// 5-tuple's (RFC 8656 section 2.2: a second allocation "must" use "a different 5-tuple";
/// an Allocate on one in use is answered 437, section 7.2). When every base is taken by a
/// retiring link (one socket, the same server), that link is released first and its base
/// is used: break before make. With several sockets (an allocation per base, RFC 8828
/// section 5.2) the base of a retiring link whose relayed candidate does not carry the data
/// is preferred. While the local offer that restarted ICE is not answered, nothing is
/// released (a rollback brings those allocations back, RFC 9429 section 5.7): with
/// `wait`, a UDP Allocate from that base waits for the link to be let go
/// ([`EngineTurn::five_tuple_held`], `release_retired_turn_links` at the answer).
fn turn_free_udp_base(
&mut self,
transport: TransportId,
server: SocketAddr,
wait: bool,
) -> Option<SocketAddr> {
if let Some(base) = self.turn_unused_udp_base(transport, server) {
return Some(base);
}
let holder = |l: &TurnLink, base: SocketAddr| {
l.retiring
&& l.client.is_some()
&& l.link_local == Some(base)
&& l.server == Some(server)
};
let idle_retiring = self.streams.turn.udp_base(transport, server, |base| {
self.turn_base_usable(transport, base)
&& self
.streams
.turn
.links
.iter()
.any(|l| holder(l, base) && !self.turn_relay_carries_data(l))
});
let base = match idle_retiring {
Some(base) => base,
None => self.turn_udp_base(transport, server)?,
};
if wait && self.restart_uncommitted(transport) {
debug!(
"TURN to {server}: the 5-tuple from {base} is held for a possible rollback; the Allocate waits"
);
return Some(base);
}
self.release_retiring_holder(base, server);
Some(base)
}
/// A UDP base of `transport` from which no link holds an allocation, or tries one, to
/// `server` (and no 437 was answered on that 5-tuple lately).
fn turn_unused_udp_base(
&self,
transport: TransportId,
server: SocketAddr,
) -> Option<SocketAddr> {
let taken = |links: &[TurnLink], base: SocketAddr| {
links.iter().any(|l| {
l.on_datagrams()
&& ((l.client.is_some()
&& l.link_local == Some(base)
&& l.server == Some(server))
|| l.udp_attempts
.iter()
.any(|a| a.base == base && a.remote == server))
})
};
let now = self.pipeline_context.now;
self.streams.turn.udp_base(transport, server, |base| {
self.turn_base_usable(transport, base)
&& !taken(&self.streams.turn.links, base)
&& !self.streams.turn.is_mismatched(base, server, now)
})
}
/// Releases the retiring link holding the 5-tuple (`base`, `server`): a new allocation
/// needs it (break before make, `OnTurnAllocationReplacedInPlace`).
fn release_retiring_holder(&mut self, base: SocketAddr, server: SocketAddr) {
for i in 0..self.streams.turn.links.len() {
let l = &self.streams.turn.links[i];
if l.retiring
&& l.client.is_some()
&& l.link_local == Some(base)
&& l.server == Some(server)
{
debug!(
"{}: its 5-tuple ({base} to {server}) is needed by a new allocation: released first",
l.url
);
let url = l.url_string();
self.release_turn_link_in_place(i);
self.pipeline_context.event_outs.push_back(
crate::peer_connection::event::RTCPeerConnectionEvent::OnTurnAllocationReplacedInPlace {
url,
local_address: base,
},
);
}
}
}
}
impl RTCPeerConnection {
/// A UDP host candidate the application added (`candidate_value`), on the active
/// transport: its base is where that transport's DTLS links start (RFC 7350). Whether ICE
/// took the candidate does not matter (with the `relay` policy it does not): the socket is
/// the application's either way.
pub(crate) fn note_udp_base_for_turn(&mut self, candidate_value: &str) {
if !(self.streams.turn.enabled
|| self.streams.turn.relay_gathering == RelayGathering::Engine)
|| self.is_closed()
{
return;
}
let Ok(candidate) = ice::candidate::unmarshal_candidate(candidate_value) else {
return;
};
if candidate.candidate_type() != ice::candidate::CandidateType::Host
|| candidate.network_type().is_tcp()
{
return;
}
let Ok(ip) = candidate.address().parse::<IpAddr>() else {
return;
};
let on = self.pipeline_context.transports.active_id();
self.streams
.turn
.note_udp_base(on, SocketAddr::new(ip, candidate.port()));
self.start_turn_links();
let usable = self
.streams
.turn
.udp_bases
.iter()
.filter(|(t, b)| *t == on && self.turn_base_usable(on, *b))
.count();
let before = self.streams.turn.links.len();
self.streams.turn.add_links_for_bases(on, usable);
if self.streams.turn.links.len() > before {
self.start_turn_links();
}
// An Allocate held for a 5-tuple can leave from the new base.
let now = self.pipeline_context.now;
self.start_waiting_udp_attempts(now);
}
/// The DTLS client configuration of a link to `host` (RFC 7350 section 4, RFC 8656
/// section 3.1): the server's certificate is checked against the URI's host with the roots
/// or the verifier of `with_turn_tls`; only forward-secret AEAD suites (BCP 195, RFC 7350
/// 4-2: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 among them). `None` when nothing could
/// verify a server.
fn turn_dtls_config(&self, host: &str) -> Option<Arc<dtls::config::HandshakeConfig>> {
use dtls::cipher_suite::CipherSuiteId;
let provider = self.setting_engine.crypto_provider.clone()?;
let tls = self.streams.turn.tls_config();
let mut builder = dtls::config::ConfigBuilder::default()
.with_crypto_provider(provider)
.with_server_name(host.to_owned())
.with_cipher_suites(vec![
CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256,
CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256,
CipherSuiteId::Tls_Ecdhe_Ecdsa_With_ChaCha20_Poly1305_Sha256,
CipherSuiteId::Tls_Ecdhe_Rsa_With_ChaCha20_Poly1305_Sha256,
CipherSuiteId::Tls_Aes_128_Gcm_Sha256,
CipherSuiteId::Tls_Aes_256_Gcm_Sha384,
CipherSuiteId::Tls_ChaCha20_Poly1305_Sha256,
])
.with_extended_master_secret(dtls::config::ExtendedMasterSecretType::Request);
if let Some(verifier) = &tls.verifier {
builder = builder.with_server_cert_verifier(verifier.clone());
} else if let Some(roots) = &tls.roots {
builder = builder.with_roots_cas((**roots).clone());
} else if tls.webpki_roots {
#[cfg(feature = "turn-tls-webpki-roots")]
{
builder = builder.with_roots_cas(rustls::RootCertStore {
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
});
}
#[cfg(not(feature = "turn-tls-webpki-roots"))]
{
return None;
}
} else {
return None;
}
if tls.disable_tls12 {
builder = builder.with_protocol_versions(
dtls::config::DtlsVersion::Dtls1_3,
dtls::config::DtlsVersion::Dtls1_3,
);
}
match builder.build(true, None) {
Ok(config) => Some(Arc::new(config)),
Err(err) => {
debug!("TURN DTLS configuration: {err}");
None
}
}
}
/// Whether a link of `transport` may start from the UDP base `base`: not when it is a
/// transport address of a DTLS association a new one replaced (RFC 8842 section 5.1: the
/// new association's 3-tuple is a new one, the relayed one included, so its allocation
/// is made from a base the application gathered for it).
fn turn_base_usable(&self, transport: TransportId, base: SocketAddr) -> bool {
!self
.ice_transport_of(transport)
.previous_association_addresses
.contains(&base)
}
/// The UDP base of `transport` of the family of `server` a link starts from
/// ([`Self::turn_base_usable`]).
fn turn_udp_base(&self, transport: TransportId, server: SocketAddr) -> Option<SocketAddr> {
self.streams.turn.udp_base(transport, server, |base| {
self.turn_base_usable(transport, base)
})
}
/// Starts a DTLS handshake to `addr` for link `index`, from the transport's UDP base of
/// that family. Returns whether it started; a link nothing can verify has failed.
fn start_dtls_attempt(&mut self, now: Instant, index: usize, addr: SocketAddr) -> bool {
let (transport, host) = {
let l = &self.streams.turn.links[index];
(l.transport, l.certificate_name().to_owned())
};
let base = if self.streams.turn.links[index].extra_base {
// Only a base no other link to the server uses: one allocation per interface.
let turn = &self.streams.turn;
turn.udp_base(transport, addr, |b| {
self.turn_base_usable(transport, b) && !turn.five_tuple_used(b, addr)
})
} else {
self.turn_free_udp_base(transport, addr, false)
};
let Some(base) = base else {
debug!("TURN over DTLS to {addr}: no UDP base of that family");
return false;
};
let Some(config) = self.turn_dtls_config(&host) else {
debug!("turns: DTLS server without roots or a verifier to check it: not used");
self.streams.turn.links[index].state = LinkState::Failed;
return false;
};
let mut endpoint = dtls::endpoint::Endpoint::new(base, TransportProtocol::UDP, None);
if let Err(err) = endpoint.connect(now, addr, config, None) {
debug!("TURN over DTLS to {addr}: {err}");
return false;
}
let mut attempt = DtlsAttempt {
remote: addr,
base,
endpoint,
};
attempt.flush(&mut self.pipeline_context.write_outs);
self.streams.turn.links[index].dtls_attempts.push(attempt);
true
}
/// Takes a datagram of a DTLS link (from a server's address to the base an association
/// runs on) before ICE sees it; returns anything else.
pub(crate) fn take_turn_dtls(&mut self, msg: TaggedBytesMut) -> Option<TaggedBytesMut> {
if msg.transport.transport_protocol != TransportProtocol::UDP
|| !msg.message.first().is_some_and(|b| (20..=63).contains(b))
{
return Some(msg);
}
let (base, remote) = (msg.transport.local_addr, msg.transport.peer_addr);
let Some(index) = self.streams.turn.link_of_dtls(base, remote) else {
return Some(msg);
};
let now = msg.now;
let won = self.streams.turn.links[index]
.dtls
.as_ref()
.is_some_and(|a| a.base == base && a.remote == remote);
let link = &mut self.streams.turn.links[index];
let Some(attempt) = link.dtls_to(base, remote) else {
return Some(msg);
};
let result = attempt
.endpoint
.read(now, remote, msg.transport.ecn, msg.message);
attempt.flush(&mut self.pipeline_context.write_outs);
match result {
Err(err) => {
debug!("TURN over DTLS from {remote}: {err}");
let failed = attempt.endpoint.is_connection_failed(&remote)
|| attempt.endpoint.get_connection_state(remote).is_none();
if failed {
self.turn_dtls_ended(now, index, base, remote, won);
}
}
Ok(events) => {
for event in events {
match event {
dtls::endpoint::EndpointEvent::HandshakeComplete if !won => {
self.turn_dtls_won(now, index, base, remote);
}
dtls::endpoint::EndpointEvent::ApplicationData(data) => {
let link = &mut self.streams.turn.links[index];
if let Some(client) = link.client.as_mut()
&& let Err(err) = client.handle_read(TaggedBytesMut {
now,
transport: TransportContext {
local_addr: base,
peer_addr: remote,
transport_protocol: TransportProtocol::UDP,
ecn: None,
},
message: data,
})
{
debug!("TURN message from {remote}: {err}");
}
}
dtls::endpoint::EndpointEvent::PeerClosed => {
self.turn_dtls_ended(now, index, base, remote, won);
}
_ => {}
}
}
}
}
self.pump_turn(now);
None
}
/// A DTLS handshake of link `index` completed: the race is won, the TURN client starts
/// over the association, with UDP's retransmissions (RFC 7350 section 4).
fn turn_dtls_won(&mut self, now: Instant, index: usize, base: SocketAddr, remote: SocketAddr) {
let gathering_rto = self.gathering_rto();
if self.streams.turn.links[index].state == LinkState::Connecting {
let rtt = self.turn_attempt_rtt(index, remote, now);
self.streams.history.succeeded(base.ip(), remote, rtt);
}
let options = self
.streams
.turn
.allocate_options(self.streams.turn.links[index].transport);
let link = &mut self.streams.turn.links[index];
if link.state != LinkState::Connecting {
return;
}
let Some(position) = link
.dtls_attempts
.iter()
.position(|a| a.base == base && a.remote == remote)
else {
return;
};
let winner = link.dtls_attempts.remove(position);
for mut loser in std::mem::take(&mut link.dtls_attempts) {
let r = loser.remote;
let _ = loser.endpoint.stop(now, r);
loser.flush(&mut self.pipeline_context.write_outs);
}
if let Some(race) = link.race.as_mut() {
race.succeeded();
}
link.dtls = Some(winner);
link.state = LinkState::OpenDtls;
link.server = Some(remote);
link.link_local = Some(base);
let Some(provider) = self.setting_engine.crypto_provider.clone() else {
link.state = LinkState::Failed;
return;
};
let config = turn::client::ClientConfig {
stun_serv_addr: remote.to_string(),
turn_serv_addr: remote.to_string(),
local_addr: base,
transport_protocol: TransportProtocol::UDP,
username: link.url.username.clone(),
password: link.url.password.clone(),
realm: String::new(),
// RFC 8445 section 14.3 (`gathering_rto`).
rto_in_ms: u64::try_from(gathering_rto.as_millis()).unwrap_or(u64::MAX),
allocation_refresh_interval_cap: self
.setting_engine
.turn_allocation_refresh_interval_cap,
software: self.setting_engine.turn_software(),
// Over DTLS: RFC 8656 section 21.1.6 is met by the association.
..Default::default()
};
let resends = self.setting_engine.stun_server_error_resends;
let unauthenticated = self.setting_engine.turn_unauthenticated_allocations;
let engine_turn = &self.streams.turn;
let made = turn::client::Client::new(config, provider).and_then(|mut client| {
client.set_server_error_resends(resends);
client.set_unauthenticated_allocations(unauthenticated);
engine_turn.seed_turn_client(&mut client);
client.allocate_with(now, options)?;
Ok(client)
});
let link = &mut self.streams.turn.links[index];
match made {
Ok(client) => link.client = Some(client),
Err(err) => {
debug!("TURN client for {}: {err}", link.url);
link.state = LinkState::Failed;
}
}
}
/// A DTLS association of link `index` failed or was closed: a racing one fails its
/// address; the one that won takes the allocation with it.
fn turn_dtls_ended(
&mut self,
now: Instant,
index: usize,
base: SocketAddr,
remote: SocketAddr,
won: bool,
) {
if won {
debug!("TURN over DTLS to {remote} ended: its allocation is gone");
// RFC 6544 section 11.2: "Similar measures SHOULD apply also to other types of
// relaying servers".
self.turn_allocation_lost(now, index);
return;
}
let link = &mut self.streams.turn.links[index];
link.dtls_attempts
.retain(|a| !(a.base == base && a.remote == remote));
if link.state == LinkState::Connecting {
if let Some(race) = link.race.as_mut() {
race.failed();
}
// RFC 8305 section 4: the handshake from this base failed.
self.streams.history.failed(base.ip(), remote);
self.drive_turn_races(now);
}
}
/// The DTLS associations' timers: handshake retransmissions and give-up.
fn turn_dtls_timeouts(&mut self, now: Instant) {
let mut ended = vec![];
for (index, link) in self.streams.turn.links.iter_mut().enumerate() {
let won = link.dtls.as_mut().map(|a| (a, true));
let racing = link.dtls_attempts.iter_mut().map(|a| (a, false));
for (a, won) in won.into_iter().chain(racing) {
let remote = a.remote;
if !a.endpoint.poll_timeout(&remote).is_some_and(|t| t <= now) {
continue;
}
let result = a.endpoint.handle_timeout(remote, now);
a.flush(&mut self.pipeline_context.write_outs);
if let Err(err) = result {
debug!("TURN over DTLS to {remote}: {err}");
ended.push((index, a.base, remote, won));
}
}
}
for (index, base, remote, won) in ended {
self.turn_dtls_ended(now, index, base, remote, won);
}
}
/// `close()`: every DTLS association says close_notify, every allocation over UDP is
/// deleted (a Refresh of LIFETIME 0, RFC 8656 section 8).
pub(crate) fn close_turn_dtls(&mut self) {
let now = self.pipeline_context.now;
for link in self.streams.turn.links.iter_mut() {
for a in link.dtls.iter_mut().chain(link.dtls_attempts.iter_mut()) {
let _ = a.endpoint.close(now);
a.flush(&mut self.pipeline_context.write_outs);
}
release_udp_allocation(
link,
now,
&mut self.pipeline_context.write_outs,
&mut self.streams.turn.releases,
);
}
// The Allocates that lost a race and are still unanswered: an answer that is an
// allocation has it deleted.
for loser in std::mem::take(&mut self.streams.turn.udp_losers) {
self.streams.turn.releases.push(UdpRelease {
url: loser.url,
base: loser.base,
server: loser.remote,
client: loser.client,
relay: None,
signed: false,
done: false,
});
}
self.pump_turn_releases(now);
}
/// Moves the releases on (`UdpRelease`): what their clients send leaves from their base,
/// an Allocate success is deleted at once, and a release that is done is dropped with an
/// `OnTurnAllocationReleased`: its Refresh of LIFETIME 0 was answered (or 437) or timed
/// out, or the Allocate was answered without an allocation, refused, or timed out.
pub(crate) fn pump_turn_releases(&mut self, now: Instant) {
for r in self.streams.turn.releases.iter_mut() {
while let Some(event) = r.client.poll_event() {
match event {
turn::client::Event::AllocateResponse(_, relay) => {
debug!("{}: an allocation nobody needs ({relay}): deleted", r.url);
if let Ok(mut x) = r.client.relay(relay) {
let _ = x.close(now);
}
r.relay = Some(relay);
r.signed = true;
}
turn::client::Event::AllocationReleased(_) => r.done = true,
turn::client::Event::AllocateError(..)
| turn::client::Event::TransactionTimeout(_)
if r.relay.is_none() =>
{
r.done = true
}
_ => {}
}
}
while let Some(t) = r.client.poll_write() {
if r.done {
continue;
}
self.pipeline_context.write_outs.push_back(TaggedBytesMut {
now,
transport: udp_context(r.base, r.server),
message: t.message,
});
}
// Nothing under way any more (no allocation was ever asked with the credential).
if r.relay.is_none() && r.client.poll_timeout().is_none() {
r.done = true;
}
}
let delay = self.setting_engine.turn_reallocation_delay;
self.streams.turn.freed.retain(|(_, _, at)| now < *at);
let mut ended = false;
let mut i = 0;
while i < self.streams.turn.releases.len() {
if !self.streams.turn.releases[i].done {
i += 1;
continue;
}
let r = self.streams.turn.releases.remove(i);
debug!("{}: released from {}", r.url, r.base);
ended = true;
if !delay.is_zero() {
self.streams
.turn
.freed
.push((r.base, r.server, now + delay));
}
self.pipeline_context.event_outs.push_back(
crate::peer_connection::event::RTCPeerConnectionEvent::OnTurnAllocationReleased {
url: r.url,
local_address: r.base,
relayed_address: r.relay,
},
);
}
// An Allocate that waited for one of these 5-tuples leaves now.
if ended {
self.start_waiting_udp_attempts(now);
}
}
/// The releases' next timer (all a closed peer connection still has).
pub(crate) fn turn_releases_poll_timeout(&mut self) -> Option<Instant> {
self.streams
.turn
.releases
.iter_mut()
.filter_map(|r| r.client.poll_timeout())
.min()
}
/// Fires the releases' timers (retransmissions, transaction timeouts).
pub(crate) fn turn_releases_handle_timeout(&mut self, now: Instant) {
for r in self.streams.turn.releases.iter_mut() {
if r.client.poll_timeout().is_some_and(|t| t <= now)
&& let Err(err) = r.client.handle_timeout(now)
{
debug!("TURN release timer: {err}");
}
}
self.pump_turn_releases(now);
}
/// An answer to one of the releases' transactions (taken out of `handle_read` before
/// anything else sees it), or `msg` back.
pub(crate) fn take_turn_release(&mut self, msg: TaggedBytesMut) -> Option<TaggedBytesMut> {
if self.streams.turn.releases.is_empty() || !matches!(stun_class(&msg.message), Some(2 | 3))
{
return Some(msg);
}
let (base, remote) = (msg.transport.local_addr, msg.transport.peer_addr);
let mut id = [0u8; 12];
id.copy_from_slice(&msg.message[8..20]);
let tid = stun::message::TransactionId(id);
let now = msg.now;
let Some(r) = self.streams.turn.releases.iter_mut().find(|r| {
!r.done && r.base == base && r.server == remote && r.client.has_transaction(&tid)
}) else {
return Some(msg);
};
if let Err(err) = r.client.handle_read(msg) {
debug!("TURN message from {remote}: {err}");
}
if !r.signed {
// The answer to the unauthenticated Allocate. A 401 made nothing: the request with
// the credential it asks for is not sent. A success (a server that does not
// authenticate) is an allocation, deleted (`pump_turn_releases`).
while r.client.poll_write().is_some() {}
let made = std::iter::from_fn(|| r.client.poll_event()).find_map(|e| match e {
turn::client::Event::AllocateResponse(_, relay) => Some(relay),
_ => None,
});
match made {
Some(relay) => {
if let Ok(mut x) = r.client.relay(relay) {
let _ = x.close(now);
}
r.relay = Some(relay);
r.signed = true;
}
None => r.done = true,
}
}
self.pump_turn_releases(now);
None
}
/// Starts an unauthenticated Allocate to `addr` for the UDP link `index`, from the
/// transport's UDP base of that family (RFC 8656 section 3.9). Returns whether it started.
fn start_udp_attempt(&mut self, now: Instant, index: usize, addr: SocketAddr) -> bool {
let gathering_rto = self.gathering_rto();
let transport = self.streams.turn.links[index].transport;
let base = if self.streams.turn.links[index].extra_base {
// Only a base no other link to the server uses: one allocation per interface.
let turn = &self.streams.turn;
turn.udp_base(transport, addr, |b| {
self.turn_base_usable(transport, b)
&& !turn.is_mismatched(b, addr, now)
&& !turn.five_tuple_used(b, addr)
})
} else {
self.turn_free_udp_base(transport, addr, true)
};
let Some(base) = base else {
debug!("TURN over UDP to {addr}: no UDP base of that family");
return false;
};
let Some(provider) = self.setting_engine.crypto_provider.clone() else {
return false;
};
let link = &self.streams.turn.links[index];
let url = link.url_string();
let config = turn::client::ClientConfig {
stun_serv_addr: addr.to_string(),
turn_serv_addr: addr.to_string(),
local_addr: base,
transport_protocol: TransportProtocol::UDP,
username: link.url.username.clone(),
password: link.url.password.clone(),
realm: String::new(),
// RFC 8445 section 14.3 (`gathering_rto`).
rto_in_ms: u64::try_from(gathering_rto.as_millis()).unwrap_or(u64::MAX),
allocation_refresh_interval_cap: self
.setting_engine
.turn_allocation_refresh_interval_cap,
software: self.setting_engine.turn_software(),
username_anonymity_required: self.setting_engine.turn_username_identifies_user,
..Default::default()
};
// The 5-tuple's previous allocation is still being deleted: the Allocate waits for
// the release to end (`start_waiting_udp_attempts`).
let sent = !self.streams.turn.five_tuple_in_release(base, addr, now)
&& !self.streams.turn.five_tuple_held(base, addr);
let options = self.streams.turn.allocate_options(transport);
let resends = self.setting_engine.stun_server_error_resends;
let unauthenticated = self.setting_engine.turn_unauthenticated_allocations;
let engine_turn = &self.streams.turn;
let mut client = match turn::client::Client::new(config, provider).and_then(|mut c| {
c.set_server_error_resends(resends);
c.set_unauthenticated_allocations(unauthenticated);
engine_turn.seed_turn_client(&mut c);
if sent {
c.allocate_with(now, options)?;
}
Ok(c)
}) {
Ok(client) => client,
Err(err) => {
debug!("TURN client for {addr}: {err}");
return false;
}
};
if !sent {
debug!(
"TURN over UDP to {addr}: the allocation from {base} is being deleted; the Allocate waits"
);
}
while let Some(t) = client.poll_write() {
self.pipeline_context.write_outs.push_back(TaggedBytesMut {
now,
transport: udp_context(base, addr),
message: t.message,
});
}
self.streams.turn.links[index]
.udp_attempts
.push(UdpAttempt {
url,
remote: addr,
base,
client,
sent,
});
true
}
/// Sends the Allocates that waited for a release of their 5-tuple, once it has ended (and
/// the reallocation delay after it is over). One that cannot be sent fails its address.
pub(crate) fn start_waiting_udp_attempts(&mut self, now: Instant) {
if self.is_closed() {
return;
}
let mut failed = false;
for index in 0..self.streams.turn.links.len() {
let mut i = 0;
while i < self.streams.turn.links[index].udp_attempts.len() {
let a = &self.streams.turn.links[index].udp_attempts[i];
let (base, remote, sent) = (a.base, a.remote, a.sent);
// Held for a rollback while the restart was not answered: once it is, the
// holder is let go as `turn_free_udp_base` would have done.
let transport = self.streams.turn.links[index].transport;
if !sent && self.streams.turn.five_tuple_held(base, remote) {
if !self.restart_uncommitted(transport) {
self.release_retiring_holder(base, remote);
} else if self.turn_unused_udp_base(transport, remote).is_some() {
// A socket the application bound since (for the restart, say) is free:
// the Allocate leaves from it now rather than wait for the held one.
debug!(
"TURN over UDP to {remote}: a free 5-tuple appeared; the Allocate moves to it"
);
self.streams.turn.links[index].udp_attempts.remove(i);
if !self.start_udp_attempt(now, index, remote)
&& let Some(r) = self.streams.turn.links[index].race.as_mut()
{
r.failed();
failed = true;
}
continue;
}
}
let a = &self.streams.turn.links[index].udp_attempts[i];
if a.sent
|| self
.streams
.turn
.five_tuple_in_release(a.base, a.remote, now)
|| self.streams.turn.five_tuple_held(a.base, a.remote)
{
i += 1;
continue;
}
let options = self
.streams
.turn
.allocate_options(self.streams.turn.links[index].transport);
let a = &mut self.streams.turn.links[index].udp_attempts[i];
if let Err(err) = a.client.allocate_with(now, options) {
debug!("TURN client for {}: {err}", a.remote);
self.streams.turn.links[index].udp_attempts.remove(i);
if let Some(race) = self.streams.turn.links[index].race.as_mut() {
race.failed();
}
failed = true;
continue;
}
a.sent = true;
debug!(
"TURN over UDP to {}: the 5-tuple is free; Allocate sent",
a.remote
);
while let Some(t) = a.client.poll_write() {
self.pipeline_context.write_outs.push_back(TaggedBytesMut {
now,
transport: udp_context(a.base, a.remote),
message: t.message,
});
}
i += 1;
}
}
if failed {
self.drive_turn_races(now);
}
}
/// The racing Allocates over UDP: their retransmissions leave, and one that timed out (or
/// failed before any answer) fails its address: the next one starts at once.
fn pump_udp_attempts(&mut self, now: Instant) {
let mut failed = vec![];
let mut unanswered: Vec<(SocketAddr, SocketAddr)> = vec![];
for index in 0..self.streams.turn.links.len() {
let link = &mut self.streams.turn.links[index];
if link.udp_attempts.is_empty() {
continue;
}
let mut lost = vec![];
for (i, a) in link.udp_attempts.iter_mut().enumerate() {
while let Some(t) = a.client.poll_write() {
self.pipeline_context.write_outs.push_back(TaggedBytesMut {
now,
transport: udp_context(a.base, a.remote),
message: t.message,
});
}
while let Some(event) = a.client.poll_event() {
if matches!(event, turn::client::Event::TransactionTimeout(_)) {
// RFC 8305 section 4: unanswered from this base.
unanswered.push((a.base, a.remote));
}
if matches!(
event,
turn::client::Event::TransactionTimeout(_)
| turn::client::Event::AllocateError(..)
) {
debug!("TURN Allocate to {}: no answer", a.remote);
lost.push(i);
}
}
}
lost.dedup();
for i in lost.into_iter().rev() {
link.udp_attempts.remove(i);
if let Some(race) = link.race.as_mut() {
race.failed();
}
failed.push(index);
}
}
for (base, remote) in unanswered {
self.streams.history.failed(base.ip(), remote);
}
if !failed.is_empty() {
self.drive_turn_races(now);
}
}
/// Takes a datagram of a UDP link (from a server's address to the base it runs on) before
/// ICE sees it: an answer to one of its transactions, or a Data indication or ChannelData
/// on its allocation; returns anything else (the application's own TURN client may share
/// the socket).
pub(crate) fn take_turn_udp(&mut self, msg: TaggedBytesMut) -> Option<TaggedBytesMut> {
if msg.transport.transport_protocol != TransportProtocol::UDP
|| (self.streams.turn.links.is_empty()
&& self.streams.turn.udp_losers.is_empty()
&& self.streams.turn.releases.is_empty())
{
return Some(msg);
}
let msg = self.take_turn_release(msg)?;
let class = stun_class(&msg.message);
let channel_data = msg.message.len() >= 4 && (0x40..=0x4f).contains(&msg.message[0]);
if class.is_none() && !channel_data {
return Some(msg);
}
let (base, remote) = (msg.transport.local_addr, msg.transport.peer_addr);
let now = msg.now;
let response = matches!(class, Some(2 | 3));
let tid = (msg.message.len() >= 20).then(|| {
let mut id = [0u8; 12];
id.copy_from_slice(&msg.message[8..20]);
stun::message::TransactionId(id)
});
// The answer to an Allocate that lost its race.
if response
&& let Some(tid) = tid
&& let Some(i) = self.streams.turn.udp_losers.iter().position(|l| {
l.base == base && l.remote == remote && l.client.has_transaction(&tid)
})
{
let mut loser = self.streams.turn.udp_losers.remove(i);
self.turn_udp_loser_answered(now, &mut loser, msg);
return None;
}
let Some(index) = self.streams.turn.link_of_udp(base, remote) else {
return Some(msg);
};
let link = &mut self.streams.turn.links[index];
if link.state == LinkState::OpenUdp {
let ours = match (class, tid) {
(Some(2 | 3), Some(tid)) => link
.client
.as_ref()
.is_some_and(|c| c.has_transaction(&tid)),
// A Data indication; ChannelData.
(Some(1), _) | (None, _) => link.relay.is_some(),
_ => false,
};
if !ours {
return Some(msg);
}
if let Some(client) = link.client.as_mut()
&& let Err(err) = client.handle_read(msg)
{
debug!("TURN message from {remote}: {err}");
}
self.pump_turn(now);
return None;
}
// The first answer of the race (a 401, or a success from a server that does not
// authenticate) wins it (RFC 8656 section 3.9).
let Some(tid) = tid.filter(|_| response) else {
return Some(msg);
};
let Some(position) = link
.udp_attempts
.iter()
.position(|a| a.base == base && a.remote == remote && a.client.has_transaction(&tid))
else {
return Some(msg);
};
if let Err(err) = link.udp_attempts[position].client.handle_read(msg) {
debug!("TURN message from {remote}: {err}");
}
self.turn_udp_won(now, index, position);
self.pump_turn(now);
None
}
/// Attempt `position` of UDP link `index` was answered first: its client runs on, the
/// others lose (kept until their answer: `turn_udp_loser_answered`).
fn turn_udp_won(&mut self, now: Instant, index: usize, position: usize) {
if self.streams.turn.links[index].state != LinkState::Connecting {
return;
}
let (base, remote) = {
let a = &self.streams.turn.links[index].udp_attempts[position];
(a.base, a.remote)
};
let rtt = self.turn_attempt_rtt(index, remote, now);
self.streams.history.succeeded(base.ip(), remote, rtt);
let link = &mut self.streams.turn.links[index];
let winner = link.udp_attempts.remove(position);
self.streams.turn.udp_losers.extend(
std::mem::take(&mut link.udp_attempts)
.into_iter()
.filter(|a| a.sent),
);
if let Some(race) = link.race.as_mut() {
race.succeeded();
}
link.state = LinkState::OpenUdp;
link.server = Some(winner.remote);
link.link_local = Some(winner.base);
link.client = Some(winner.client);
let _ = now;
}
/// The answer to an Allocate that lost its race (RFC 8656 section 3.9): a 401 is dropped
/// (the connection "silently abandoned"), an allocation a server without authentication
/// made is deleted with a Refresh of LIFETIME 0.
fn turn_udp_loser_answered(
&mut self,
now: Instant,
loser: &mut UdpAttempt,
msg: TaggedBytesMut,
) {
let _ = loser.client.handle_read(msg);
// What the answer made the client send (the signed request after a 401) stays unsent.
while loser.client.poll_write().is_some() {}
let mut relayed = None;
while let Some(event) = loser.client.poll_event() {
if let turn::client::Event::AllocateResponse(_, addr) = event {
relayed = Some(addr);
}
}
let Some(relayed) = relayed else {
return;
};
debug!(
"TURN over UDP: the allocation {relayed} on {} lost the race; deleted",
loser.remote
);
if let Ok(mut relay) = loser.client.relay(relayed) {
let _ = relay.close(now);
}
while let Some(t) = loser.client.poll_write() {
self.pipeline_context.write_outs.push_back(TaggedBytesMut {
now,
transport: udp_context(loser.base, loser.remote),
message: t.message,
});
}
}
/// A relayed candidate the application added itself (`candidate_value`, `url`) on the
/// active transport: the engine's UDP links for that server (any, without a `url`) on that
/// transport are left to it. One whose relayed candidate the engine has not announced yet
/// stops (an allocation it holds is deleted); one already announced stays, since a
/// signalled candidate cannot be taken back.
pub(crate) fn note_application_relay(&mut self, candidate_value: &str, url: Option<&str>) {
let Ok(candidate) = ice::candidate::unmarshal_candidate(candidate_value) else {
return;
};
if candidate.candidate_type() != ice::candidate::CandidateType::Relay
|| candidate.network_type().is_tcp()
|| self.streams.turn.link_of_relay(candidate.addr()).is_some()
{
return;
}
let on = self.pipeline_context.transports.active_id();
let url = url.map(str::to_owned);
if !self
.streams
.turn
.application_relays
.contains(&(on, url.clone()))
{
self.streams.turn.application_relays.push((on, url));
}
let now = self.pipeline_context.now;
for index in 0..self.streams.turn.links.len() {
let link = &self.streams.turn.links[index];
if !self.streams.turn.left_to_application(link) || link.announced_ufrag.is_some() {
continue;
}
debug!(
"{}: the application gathers from it; the engine stops",
link.url
);
let link = &mut self.streams.turn.links[index];
release_udp_allocation(
link,
now,
&mut self.pipeline_context.write_outs,
&mut self.streams.turn.releases,
);
link.client = None;
link.relay = None;
link.relay_more.clear();
link.race = None;
link.state = LinkState::Failed;
}
self.finish_deferred_gathering();
}
}
#[cfg(test)]
mod tests {
use super::*;
/// RFC 8656 section 3.1, RFC 7350 section 4.1: `turn:...?transport=tcp` (TCP), `turns:`
/// (TLS over TCP), `turns:...?transport=udp` (DTLS) and `turn:` over UDP servers get a link
/// per transport; with `RelayGathering::Application` a `turn:` server over UDP gets none.
#[test]
fn turn_servers_get_a_link_per_transport_over_udp_only_when_the_engine_gathers() {
let urls: Vec<Url> = [
"turn:192.0.2.1:3478?transport=tcp",
"turns:turn.example:5349",
"turns:192.0.2.1:5349?transport=tcp",
"turn:192.0.2.1:3478",
"turns:192.0.2.1:5349?transport=udp",
"stun:192.0.2.1:3478",
]
.iter()
.map(|u| Url::parse_url(u).unwrap())
.collect();
let mut turn = EngineTurn::new(&urls, true, TurnTlsConfig::default());
// The TCP allocations beside: `a_tcp_or_tls_server_gets_a_tcp_allocation_link_too`.
turn.tcp_relay = false;
assert!(
turn.links.is_empty(),
"no link before a transport needs one"
);
let first = TransportId::default();
turn.make_links(first, "u1");
turn.make_links(first, "u1");
let links: Vec<(String, RTCIceServerTransportProtocol)> = turn
.links
.iter()
.map(|l| (l.url_string(), l.protocol()))
.collect();
assert_eq!(
links,
vec![
(
"turn:192.0.2.1:3478?transport=tcp".to_owned(),
RTCIceServerTransportProtocol::Tcp
),
(
"turns:turn.example:5349?transport=tcp".to_owned(),
RTCIceServerTransportProtocol::Tls
),
(
"turns:192.0.2.1:5349?transport=tcp".to_owned(),
RTCIceServerTransportProtocol::Tls
),
(
"turn:192.0.2.1:3478?transport=udp".to_owned(),
RTCIceServerTransportProtocol::Udp
),
(
"turns:192.0.2.1:5349?transport=udp".to_owned(),
RTCIceServerTransportProtocol::Dtls
),
]
);
// Nothing started: nothing pending for the end of gathering.
assert!(!turn.pending(first, true));
// Another transport gets links of its own, once.
turn.make_links(TransportId(1), "u1");
assert_eq!(turn.links.len(), 10);
assert!(
turn.links[5..]
.iter()
.all(|l| l.transport == TransportId(1))
);
// The application gathers from `turn:` over UDP: no link for it.
let mut turn = EngineTurn::new(&urls, true, TurnTlsConfig::default());
turn.tcp_relay = false;
turn.relay_gathering = RelayGathering::Application;
turn.make_links(first, "u1");
assert_eq!(turn.links.len(), 4);
assert!(turn.links.iter().all(|l| l.carrier != Carrier::Udp));
}
/// RFC 6062 section 4.1 with RFC 6544 section 5.5: a server over TCP or TLS gets a second
/// link for a TCP allocation (its own control connection: an allocation is its 5-tuple's);
/// one over DTLS none (a TCP allocation needs TCP or TLS to the server).
#[test]
fn a_tcp_or_tls_server_gets_a_tcp_allocation_link_too() {
let urls: Vec<Url> = [
"turn:192.0.2.1:3478?transport=tcp",
"turns:192.0.2.1:5349?transport=tcp",
"turns:192.0.2.1:5349?transport=udp",
]
.iter()
.map(|u| Url::parse_url(u).unwrap())
.collect();
let mut turn = EngineTurn::new(&urls, true, TurnTlsConfig::default());
turn.make_links(TransportId::default(), "u1");
let links: Vec<(RTCIceServerTransportProtocol, bool)> = turn
.links
.iter()
.map(|l| (l.protocol(), l.relay_tcp))
.collect();
assert_eq!(
links,
vec![
(RTCIceServerTransportProtocol::Tcp, false),
(RTCIceServerTransportProtocol::Tcp, true),
(RTCIceServerTransportProtocol::Tls, false),
(RTCIceServerTransportProtocol::Tls, true),
(RTCIceServerTransportProtocol::Dtls, false),
]
);
}
}