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

/**
 * \file entrynodes.c
 * \brief Code to manage our fixed first nodes for various functions.
 *
 * Entry nodes can be guards (for general use) or bridges (for censorship
 * circumvention).
 *
 * In general, we use entry guards to prevent traffic-sampling attacks:
 * if we chose every circuit independently, an adversary controlling
 * some fraction of paths on the network would observe a sample of every
 * user's traffic. Using guards gives users a chance of not being
 * profiled.
 *
 * The current entry guard selection code is designed to try to avoid
 * _ever_ trying every guard on the network, to try to stick to guards
 * that we've used before, to handle hostile/broken networks, and
 * to behave sanely when the network goes up and down.
 *
 * Our algorithm works as follows: First, we maintain a SAMPLE of guards
 * we've seen in the networkstatus consensus.  We maintain this sample
 * over time, and store it persistently; it is chosen without reference
 * to our configuration or firewall rules.  Guards remain in the sample
 * as they enter and leave the consensus.  We expand this sample as
 * needed, up to a maximum size.
 *
 * As a subset of the sample, we maintain a FILTERED SET of the guards
 * that we would be willing to use if we could connect to them.  The
 * filter removes all the guards that we're excluding because they're
 * bridges (or not bridges), because we have restrictive firewall rules,
 * because of ExcludeNodes, because we of path bias restrictions,
 * because they're absent from the network at present, and so on.
 *
 * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
 * (also called a "usable filtered set") of those guards that we call
 * "reachable" or "maybe reachable".  A guard is reachable if we've
 * connected to it more recently than we've failed.  A guard is "maybe
 * reachable" if we have never tried to connect to it, or if we
 * failed to connect to it so long ago that we no longer think our
 * failure means it's down.
 *
 * As a persistent ordered list whose elements are taken from the
 * sampled set, we track a CONFIRMED GUARDS LIST.  A guard becomes
 * confirmed when we successfully build a circuit through it, and decide
 * to use that circuit.
 *
 * And as a final group, we have an ordered list of PRIMARY GUARDS,
 * whose elements are taken from the filtered set. We prefer
 * confirmed guards to non-confirmed guards for this list, and place
 * other restrictions on it.  The primary guards are the ones that we
 * connect to "when nothing is wrong" -- circuits through them can be used
 * immediately.
 *
 * To build circuits, we take a primary guard if possible -- or a
 * reachable filtered confirmed guard if no primary guard is possible --
 * or the first (by sampled order) filtered guard otherwise.  If the guard is
 * primary, we can use the circuit immediately on success.  Otherwise,
 * the guard is now "pending" -- we won't use its circuit unless all
 * of the circuits we're trying to build through better guards have
 * definitely failed.
 *
 * While we're building circuits, we track a little "guard state" for
 * each circuit. We use this to keep track of whether the circuit is
 * one that we can use as soon as it's done, or whether it's one that
 * we should keep around to see if we can do better.  In the latter case,
 * a periodic call to entry_guards_upgrade_waiting_circuits() will
 * eventually upgrade it.
 **/
/* DOCDOC -- expand this.
 *
 * Information invariants:
 *
 * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
 *
 * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
 * flag is set, set its usable_filtered flag.
 *
 * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
 *
 * [x] Whenever the configuration changes in a relevant way, update the
 * filtered/usable flags. (LATER.)
 *
 * [x] Whenever we add a guard to the sample, make sure its filtered/usable
 * flags are set as possible.
 *
 * [x] Whenever we remove a guard from the sample, remove it from the primary
 * and confirmed lists.
 *
 * [x] When we make a guard confirmed, update the primary list, and sort them
 * by sampled order.
 *
 * [x] When we make a guard filtered or unfiltered, update the primary list.
 *
 * [x] When we are about to pick a guard, make sure that the primary list is
 * full.
 *
 * [x] When we update the confirmed list, or when we re-build the primary list
 * and detect a change, we sort those lists by sampled_idx
 *
 * [x] Before calling first_reachable_filtered_entry_guard(), make sure
 * that the filtered, primary, and confirmed flags are up-to-date.
 *
 * [x] Call entry_guard_consider_retry every time we are about to check
 * is_usable_filtered or is_reachable, and every time we set
 * is_filtered to 1.
 *
 * [x] Call entry_guards_changed_for_guard_selection() whenever we update
 * a persistent field.
 */

#define ENTRYNODES_PRIVATE

#include "core/or/or.h"
#include "app/config/config.h"
#include "lib/confmgt/confmgt.h"
#include "app/config/statefile.h"
#include "core/mainloop/connection.h"
#include "core/mainloop/mainloop.h"
#include "core/or/channel.h"
#include "core/or/circuitbuild.h"
#include "core/or/circuitlist.h"
#include "core/or/circuitstats.h"
#include "core/or/circuituse.h"
#include "core/or/policies.h"
#include "feature/client/bridges.h"
#include "feature/client/circpathbias.h"
#include "feature/client/entrynodes.h"
#include "feature/client/transports.h"
#include "feature/control/control_events.h"
#include "feature/dirclient/dlstatus.h"
#include "feature/dircommon/directory.h"
#include "feature/nodelist/describe.h"
#include "feature/nodelist/microdesc.h"
#include "feature/nodelist/networkstatus.h"
#include "feature/nodelist/nickname.h"
#include "feature/nodelist/nodelist.h"
#include "feature/nodelist/node_select.h"
#include "feature/nodelist/routerset.h"
#include "feature/relay/router.h"
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/digestset.h"
#include "lib/encoding/confline.h"
#include "lib/math/fp.h"

#include "feature/nodelist/node_st.h"
#include "core/or/origin_circuit_st.h"
#include "app/config/or_state_st.h"

/** A list of existing guard selection contexts. */
static smartlist_t *guard_contexts = NULL;
/** The currently enabled guard selection context. */
static guard_selection_t *curr_guard_context = NULL;

/** A value of 1 means that at least one context has changed,
 * and those changes need to be flushed to disk. */
static int entry_guards_dirty = 0;

static void entry_guard_set_filtered_flags(const or_options_t *options,
                                           guard_selection_t *gs,
                                           entry_guard_t *guard);
static void pathbias_check_use_success_count(entry_guard_t *guard);
static void pathbias_check_close_success_count(entry_guard_t *guard);
static int node_is_possible_guard(const node_t *node);
static int node_passes_guard_filter(const or_options_t *options,
                                    const node_t *node);
static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs,
                               const uint8_t *rsa_id_digest,
                               const char *nickname,
                               const tor_addr_port_t *bridge_addrport);
static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
                                              const tor_addr_port_t *addrport);
static int entry_guard_obeys_restriction(const entry_guard_t *guard,
                                         const entry_guard_restriction_t *rst);
static int compare_guards_by_sampled_idx(const void **a_, const void **b_);

/** Return 0 if we should apply guardfraction information found in the
 *  consensus. A specific consensus can be specified with the
 *  <b>ns</b> argument, if NULL the most recent one will be picked.*/
int
should_apply_guardfraction(const networkstatus_t *ns)
{
  /* We need to check the corresponding torrc option and the consensus
   * parameter if we need to. */
  const or_options_t *options = get_options();

  /* If UseGuardFraction is 'auto' then check the same-named consensus
   * parameter. If the consensus parameter is not present, default to
   * "off". */
  if (options->UseGuardFraction == -1) {
    return networkstatus_get_param(ns, "UseGuardFraction",
                                   0, /* default to "off" */
                                   0, 1);
  }

  return options->UseGuardFraction;
}

/** Return true iff we know a preferred descriptor for <b>guard</b> */
static int
guard_has_descriptor(const entry_guard_t *guard)
{
  const node_t *node = node_get_by_id(guard->identity);
  if (!node)
    return 0;
  return node_has_preferred_descriptor(node, 1);
}

/**
 * Try to determine the correct type for a selection named "name",
 * if <b>type</b> is GS_TYPE_INFER.
 */
STATIC guard_selection_type_t
guard_selection_infer_type(guard_selection_type_t type,
                           const char *name)
{
  if (type == GS_TYPE_INFER) {
    if (!strcmp(name, "bridges"))
      type = GS_TYPE_BRIDGE;
    else if (!strcmp(name, "restricted"))
      type = GS_TYPE_RESTRICTED;
    else
      type = GS_TYPE_NORMAL;
  }
  return type;
}

/**
 * Allocate and return a new guard_selection_t, with the name <b>name</b>.
 */
STATIC guard_selection_t *
guard_selection_new(const char *name,
                    guard_selection_type_t type)
{
  guard_selection_t *gs;

  type = guard_selection_infer_type(type, name);

  gs = tor_malloc_zero(sizeof(*gs));
  gs->name = tor_strdup(name);
  gs->type = type;
  gs->sampled_entry_guards = smartlist_new();
  gs->confirmed_entry_guards = smartlist_new();
  gs->primary_entry_guards = smartlist_new();

  return gs;
}

/**
 * Return the guard selection called <b>name</b>. If there is none, and
 * <b>create_if_absent</b> is true, then create and return it.  If there
 * is none, and <b>create_if_absent</b> is false, then return NULL.
 */
STATIC guard_selection_t *
get_guard_selection_by_name(const char *name,
                            guard_selection_type_t type,
                            int create_if_absent)
{
  if (!guard_contexts) {
    guard_contexts = smartlist_new();
  }
  SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
    if (!strcmp(gs->name, name))
      return gs;
  } SMARTLIST_FOREACH_END(gs);

  if (! create_if_absent)
    return NULL;

  log_debug(LD_GUARD, "Creating a guard selection called %s", name);
  guard_selection_t *new_selection = guard_selection_new(name, type);
  smartlist_add(guard_contexts, new_selection);

  return new_selection;
}

/**
 * Allocate the first guard context that we're planning to use,
 * and make it the current context.
 */
static void
create_initial_guard_context(void)
{
  tor_assert(! curr_guard_context);
  if (!guard_contexts) {
    guard_contexts = smartlist_new();
  }
  guard_selection_type_t type = GS_TYPE_INFER;
  const char *name = choose_guard_selection(
                             get_options(),
                             networkstatus_get_reasonably_live_consensus(
                                                    approx_time(),
                                                    usable_consensus_flavor()),
                             NULL,
                             &type);
  tor_assert(name); // "name" can only be NULL if we had an old name.
  tor_assert(type != GS_TYPE_INFER);
  log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
  curr_guard_context = get_guard_selection_by_name(name, type, 1);
}

/** Get current default guard_selection_t, creating it if necessary */
guard_selection_t *
get_guard_selection_info(void)
{
  if (!curr_guard_context) {
    create_initial_guard_context();
  }

  return curr_guard_context;
}

/** Return a statically allocated human-readable description of <b>guard</b>
 */
const char *
entry_guard_describe(const entry_guard_t *guard)
{
  static char buf[256];
  tor_snprintf(buf, sizeof(buf),
               "%s ($%s)",
               strlen(guard->nickname) ? guard->nickname : "[bridge]",
               hex_str(guard->identity, DIGEST_LEN));
  return buf;
}

/** Return <b>guard</b>'s 20-byte RSA identity digest */
const char *
entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
{
  return guard->identity;
}

/** Return the pathbias state associated with <b>guard</b>. */
guard_pathbias_t *
entry_guard_get_pathbias_state(entry_guard_t *guard)
{
  return &guard->pb;
}

HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)

/** Return an interval between 'now' and 'max_backdate' seconds in the past,
 * chosen uniformly at random.  We use this before recording persistent
 * dates, so that we aren't leaking exactly when we recorded it.
 */
MOCK_IMPL(STATIC time_t,
randomize_time,(time_t now, time_t max_backdate))
{
  tor_assert(max_backdate > 0);

  time_t earliest = now - max_backdate;
  time_t latest = now;
  if (earliest <= 0)
    earliest = 1;
  if (latest <= earliest)
    latest = earliest + 1;

  return crypto_rand_time_range(earliest, latest);
}

/**
 * @name parameters for networkstatus algorithm
 *
 * These parameters are taken from the consensus; some are overrideable in
 * the torrc.
 */
/**@{*/
/**
 * We never let our sampled guard set grow larger than this fraction
 * of the guards on the network.
 */
STATIC double
get_max_sample_threshold(void)
{
  int32_t pct =
    networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
                            DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
                            1, 100);
  return pct / 100.0;
}
/**
 * We never let our sampled guard set grow larger than this number.
 */
STATIC int
get_max_sample_size_absolute(void)
{
  return (int) networkstatus_get_param(NULL, "guard-max-sample-size",
                                       DFLT_MAX_SAMPLE_SIZE,
                                       1, INT32_MAX);
}
/**
 * We always try to make our sample contain at least this many guards.
 */
STATIC int
get_min_filtered_sample_size(void)
{
  return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
                                 DFLT_MIN_FILTERED_SAMPLE_SIZE,
                                 1, INT32_MAX);
}
/**
 * If a guard is unlisted for this many days in a row, we remove it.
 */
STATIC int
get_remove_unlisted_guards_after_days(void)
{
  return networkstatus_get_param(NULL,
                                 "guard-remove-unlisted-guards-after-days",
                                 DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
                                 1, 365*10);
}

/**
 * Return number of seconds that will make a guard no longer eligible
 * for selection if unlisted for this long.
 */
static time_t
get_remove_unlisted_guards_after_seconds(void)
{
  return get_remove_unlisted_guards_after_days() * 24 * 60 * 60;
}

/**
 * We remove unconfirmed guards from the sample after this many days,
 * regardless of whether they are listed or unlisted.
 */
STATIC int
get_guard_lifetime(void)
{
  if (get_options()->GuardLifetime >= 86400)
    return get_options()->GuardLifetime;
  int32_t days;
  days = networkstatus_get_param(NULL,
                                 "guard-lifetime-days",
                                 DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
  return days * 86400;
}
/**
 * We remove confirmed guards from the sample if they were sampled
 * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
 */
STATIC int
get_guard_confirmed_min_lifetime(void)
{
  if (get_options()->GuardLifetime >= 86400)
    return get_options()->GuardLifetime;
  int32_t days;
  days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
                                 DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
                                 1, 365*10);
  return days * 86400;
}
/**
 * How many guards do we try to keep on our primary guard list?
 */
STATIC int
get_n_primary_guards(void)
{
  /* If the user has explicitly configured the number of primary guards, do
   * what the user wishes to do */
  const int configured_primaries = get_options()->NumPrimaryGuards;
  if (configured_primaries) {
    return configured_primaries;
  }

  /* otherwise check for consensus parameter and if that's not set either, just
   * use the default value. */
  return networkstatus_get_param(NULL,
                                 "guard-n-primary-guards",
                                 DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
}
/**
 * Return the number of the live primary guards we should look at when
 * making a circuit.
 */
STATIC int
get_n_primary_guards_to_use(guard_usage_t usage)
{
  int configured;
  const char *param_name;
  int param_default;

  /* If the user has explicitly configured the amount of guards, use
     that. Otherwise, fall back to the default value. */
  if (usage == GUARD_USAGE_DIRGUARD) {
    configured = get_options()->NumDirectoryGuards;
    param_name = "guard-n-primary-dir-guards-to-use";
    param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE;
  } else {
    configured = get_options()->NumEntryGuards;
    param_name = "guard-n-primary-guards-to-use";
    param_default = DFLT_N_PRIMARY_GUARDS_TO_USE;
  }
  if (configured >= 1) {
    return configured;
  }
  return networkstatus_get_param(NULL,
                                 param_name, param_default, 1, INT32_MAX);
}
/**
 * If we haven't successfully built or used a circuit in this long, then
 * consider that the internet is probably down.
 */
STATIC int
get_internet_likely_down_interval(void)
{
  return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
                                 DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
                                 1, INT32_MAX);
}
/**
 * If we're trying to connect to a nonprimary guard for at least this
 * many seconds, and we haven't gotten the connection to work, we will treat
 * lower-priority guards as usable.
 */
STATIC int
get_nonprimary_guard_connect_timeout(void)
{
  return networkstatus_get_param(NULL,
                                 "guard-nonprimary-guard-connect-timeout",
                                 DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
                                 1, INT32_MAX);
}
/**
 * If a circuit has been sitting around in 'waiting for better guard' state
 * for at least this long, we'll expire it.
 */
STATIC int
get_nonprimary_guard_idle_timeout(void)
{
  return networkstatus_get_param(NULL,
                                 "guard-nonprimary-guard-idle-timeout",
                                 DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
                                 1, INT32_MAX);
}
/**
 * If our configuration retains fewer than this fraction of guards from the
 * torrc, we are in a restricted setting.
 */
STATIC double
get_meaningful_restriction_threshold(void)
{
  int32_t pct = networkstatus_get_param(NULL,
                                        "guard-meaningful-restriction-percent",
                                        DFLT_MEANINGFUL_RESTRICTION_PERCENT,
                                        1, INT32_MAX);
  return pct / 100.0;
}
/**
 * If our configuration retains fewer than this fraction of guards from the
 * torrc, we are in an extremely restricted setting, and should warn.
 */
STATIC double
get_extreme_restriction_threshold(void)
{
  int32_t pct = networkstatus_get_param(NULL,
                                        "guard-extreme-restriction-percent",
                                        DFLT_EXTREME_RESTRICTION_PERCENT,
                                        1, 100);
  return pct / 100.0;
}

/* Mark <b>guard</b> as maybe reachable again. */
static void
mark_guard_maybe_reachable(entry_guard_t *guard)
{
  if (guard->is_reachable != GUARD_REACHABLE_NO) {
    return;
  }

  /* Note that we do not clear failing_since: this guard is now only
   * _maybe-reachable_. */
  guard->is_reachable = GUARD_REACHABLE_MAYBE;
  if (guard->is_filtered_guard)
    guard->is_usable_filtered_guard = 1;

  /* Check if it is a bridge and we don't have its descriptor yet */
  if (guard->bridge_addr && !guard_has_descriptor(guard)) {
    /* Reset the descriptor fetch retry schedule, so it gives it another
     * go soon. It's important to keep any "REACHABLE_MAYBE" bridges in
     * sync with the descriptor fetch schedule, since we will refuse to
     * use the network until our first primary bridges are either
     * known-usable or known-unusable. See bug 40396. */
    download_status_t *dl = get_bridge_dl_status_by_id(guard->identity);
    if (dl)
      download_status_reset(dl);
  }
}

/**
 * Called when the network comes up after having seemed to be down for
 * a while: Mark the primary guards as maybe-reachable so that we'll
 * try them again.
 */
STATIC void
mark_primary_guards_maybe_reachable(guard_selection_t *gs)
{
  tor_assert(gs);

  if (!gs->primary_guards_up_to_date)
    entry_guards_update_primary(gs);

  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
    mark_guard_maybe_reachable(guard);
  } SMARTLIST_FOREACH_END(guard);
}

/* Called when we exhaust all guards in our sampled set: Marks all guards as
   maybe-reachable so that we 'll try them again. */
static void
mark_all_guards_maybe_reachable(guard_selection_t *gs)
{
  tor_assert(gs);

  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    mark_guard_maybe_reachable(guard);
  } SMARTLIST_FOREACH_END(guard);
}

/**@}*/

/**
 * Given our options and our list of nodes, return the name of the
 * guard selection that we should use.  Return NULL for "use the
 * same selection you were using before.
 */
STATIC const char *
choose_guard_selection(const or_options_t *options,
                       const networkstatus_t *live_ns,
                       const guard_selection_t *old_selection,
                       guard_selection_type_t *type_out)
{
  tor_assert(options);
  tor_assert(type_out);

  if (options->UseBridges) {
    *type_out = GS_TYPE_BRIDGE;
    return "bridges";
  }

  if (! live_ns) {
    /* without a networkstatus, we can't tell any more than that. */
    *type_out = GS_TYPE_NORMAL;
    return "default";
  }

  const smartlist_t *nodes = nodelist_get_list();
  int n_guards = 0, n_passing_filter = 0;
  SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
    if (node_is_possible_guard(node)) {
      ++n_guards;
      if (node_passes_guard_filter(options, node)) {
        ++n_passing_filter;
      }
    }
  } SMARTLIST_FOREACH_END(node);

  /* We use separate 'high' and 'low' thresholds here to prevent flapping
   * back and forth */
  const int meaningful_threshold_high =
    (int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
  const int meaningful_threshold_mid =
    (int)(n_guards * get_meaningful_restriction_threshold());
  const int meaningful_threshold_low =
    (int)(n_guards * get_meaningful_restriction_threshold() * .95);
  const int extreme_threshold =
    (int)(n_guards * get_extreme_restriction_threshold());

  /*
    If we have no previous selection, then we're "restricted" iff we are
    below the meaningful restriction threshold.  That's easy enough.

    But if we _do_ have a previous selection, we make it a little
    "sticky": we only move from "restricted" to "default" when we find
    that we're above the threshold plus 5%, and we only move from
    "default" to "restricted" when we're below the threshold minus 5%.
    That should prevent us from flapping back and forth if we happen to
    be hovering very close to the default.

    The extreme threshold is for warning only.
  */

  static int have_warned_extreme_threshold = 0;
  if (n_guards &&
      n_passing_filter < extreme_threshold &&
      ! have_warned_extreme_threshold) {
    have_warned_extreme_threshold = 1;
    const double exclude_frac =
      (n_guards - n_passing_filter) / (double)n_guards;
    log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
             "guards. That's likely to make you stand out from the "
             "rest of the world.", (int)(exclude_frac * 100));
  }

  /* Easy case: no previous selection. Just check if we are in restricted or
     normal guard selection. */
  if (old_selection == NULL) {
    if (n_passing_filter >= meaningful_threshold_mid) {
      *type_out = GS_TYPE_NORMAL;
      return "default";
    } else {
      *type_out = GS_TYPE_RESTRICTED;
      return "restricted";
    }
  }

  /* Trickier case: we do have a previous guard selection context. */
  tor_assert(old_selection);

  /* Use high and low thresholds to decide guard selection, and if we fall in
     the middle then keep the current guard selection context. */
  if (n_passing_filter >= meaningful_threshold_high) {
    *type_out = GS_TYPE_NORMAL;
    return "default";
  } else if (n_passing_filter < meaningful_threshold_low) {
    *type_out = GS_TYPE_RESTRICTED;
    return "restricted";
  } else {
    /* we are in the middle: maintain previous guard selection */
    *type_out = old_selection->type;
    return old_selection->name;
  }
}

/**
 * Check whether we should switch from our current guard selection to a
 * different one.  If so, switch and return 1.  Return 0 otherwise.
 *
 * On a 1 return, the caller should mark all currently live circuits unusable
 * for new streams, by calling circuit_mark_all_unused_circs() and
 * circuit_mark_all_dirty_circs_as_unusable().
 */
int
update_guard_selection_choice(const or_options_t *options)
{
  if (!curr_guard_context) {
    create_initial_guard_context();
    return 1;
  }

  guard_selection_type_t type = GS_TYPE_INFER;
  const char *new_name = choose_guard_selection(
                             options,
                             networkstatus_get_reasonably_live_consensus(
                                                    approx_time(),
                                                    usable_consensus_flavor()),
                             curr_guard_context,
                             &type);
  tor_assert(new_name);
  tor_assert(type != GS_TYPE_INFER);

  const char *cur_name = curr_guard_context->name;
  if (! strcmp(cur_name, new_name)) {
    log_debug(LD_GUARD,
              "Staying with guard context \"%s\" (no change)", new_name);
    return 0; // No change
  }

  log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
             new_name, cur_name);
  guard_selection_t *new_guard_context;
  new_guard_context = get_guard_selection_by_name(new_name, type, 1);
  tor_assert(new_guard_context);
  tor_assert(new_guard_context != curr_guard_context);
  curr_guard_context = new_guard_context;

  return 1;
}

/**
 * Return true iff <b>node</b> has all the flags needed for us to consider it
 * a possible guard when sampling guards.
 */
static int
node_is_possible_guard(const node_t *node)
{
  /* The "GUARDS" set is all nodes in the nodelist for which this predicate
   * holds. */

  tor_assert(node);
  return (node->is_possible_guard &&
          node->is_stable &&
          node->is_fast &&
          node->is_valid &&
          node_is_dir(node) &&
          !router_digest_is_me(node->identity));
}

/**
 * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
 * NULL if we don't have one. */
STATIC entry_guard_t *
get_sampled_guard_with_id(guard_selection_t *gs,
                          const uint8_t *rsa_id)
{
  tor_assert(gs);
  tor_assert(rsa_id);
  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
      return guard;
  } SMARTLIST_FOREACH_END(guard);
  return NULL;
}

/** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
 * return that guard. Otherwise return NULL. */
static entry_guard_t *
get_sampled_guard_for_bridge(guard_selection_t *gs,
                             const bridge_info_t *bridge)
{
  const uint8_t *id = bridge_get_rsa_id_digest(bridge);
  const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
  entry_guard_t *guard;
  if (BUG(!addrport))
    return NULL; // LCOV_EXCL_LINE
  guard = get_sampled_guard_by_bridge_addr(gs, addrport);
  if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN)))
    return NULL;
  else
    return guard;
}

/** If we know a bridge_info_t matching <b>guard</b>, return that
 * bridge.  Otherwise return NULL. */
static bridge_info_t *
get_bridge_info_for_guard(const entry_guard_t *guard)
{
  const uint8_t *identity = NULL;
  if (! tor_digest_is_zero(guard->identity)) {
    identity = (const uint8_t *)guard->identity;
  }
  if (BUG(guard->bridge_addr == NULL))
    return NULL;

  return get_configured_bridge_by_exact_addr_port_digest(
                                                 &guard->bridge_addr->addr,
                                                 guard->bridge_addr->port,
                                                 (const char*)identity);
}

/**
 * Return true iff we have a sampled guard with the RSA identity digest
 * <b>rsa_id</b>. */
static inline int
have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
{
  return get_sampled_guard_with_id(gs, rsa_id) != NULL;
}

/**
 * Allocate a new entry_guard_t object for <b>node</b>, add it to the
 * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
 * not currently be a sampled guard in <b>gs</b>.
 */
STATIC entry_guard_t *
entry_guard_add_to_sample(guard_selection_t *gs,
                          const node_t *node)
{
  log_info(LD_GUARD, "Adding %s to the entry guard sample set.",
           node_describe(node));

  /* make sure that the guard is not already sampled. */
  if (BUG(have_sampled_guard_with_id(gs, (const uint8_t*)node->identity)))
    return NULL; // LCOV_EXCL_LINE

  return entry_guard_add_to_sample_impl(gs,
                                        (const uint8_t*)node->identity,
                                        node_get_nickname(node),
                                        NULL);
}

/**
 * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
 * nickname, and ORPort.  rsa_id_digest and bridge_addrport are optional, but
 * we need one of them. nickname is optional. The caller is responsible for
 * maintaining the size limit of the SAMPLED_GUARDS set.
 */
static entry_guard_t *
entry_guard_add_to_sample_impl(guard_selection_t *gs,
                               const uint8_t *rsa_id_digest,
                               const char *nickname,
                               const tor_addr_port_t *bridge_addrport)
{
  const int GUARD_LIFETIME = get_guard_lifetime();
  tor_assert(gs);

  // XXXX #20827 take ed25519 identity here too.

  /* Make sure we can actually identify the guard. */
  if (BUG(!rsa_id_digest && !bridge_addrport))
    return NULL; // LCOV_EXCL_LINE

  entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));

  /* persistent fields */
  guard->is_persistent = (rsa_id_digest != NULL);
  guard->selection_name = tor_strdup(gs->name);
  if (rsa_id_digest)
    memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
  if (nickname)
    strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
  tor_free(guard->sampled_by_version);
  guard->sampled_by_version = tor_strdup(VERSION);
  guard->currently_listed = 1;
  guard->sampled_idx = gs->next_sampled_idx++;
  guard->confirmed_idx = -1;

  /* non-persistent fields */
  guard->is_reachable = GUARD_REACHABLE_MAYBE;
  if (bridge_addrport)
    guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));

  smartlist_add(gs->sampled_entry_guards, guard);
  guard->in_selection = gs;
  entry_guard_set_filtered_flags(get_options(), gs, guard);
  entry_guards_changed_for_guard_selection(gs);

  /* Just added this guard to the sampled set and hence it might be used as a
   * guard in the future: send GUARD NEW control event. */
  control_event_guard(guard->nickname, guard->identity, "NEW");

  return guard;
}

/**
 * Add an entry guard to the "bridges" guard selection sample, with
 * information taken from <b>bridge</b>. Return that entry guard.
 */
static entry_guard_t *
entry_guard_add_bridge_to_sample(guard_selection_t *gs,
                                 const bridge_info_t *bridge)
{
  const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge);
  const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);

  tor_assert(addrport);

  /* make sure that the guard is not already sampled. */
  if (BUG(get_sampled_guard_for_bridge(gs, bridge)))
    return NULL; // LCOV_EXCL_LINE

  return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport);
}

/**
 * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
 * or NULL if none exists.
*/
static entry_guard_t *
get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
                                 const tor_addr_port_t *addrport)
{
  if (! gs)
    return NULL;
  if (BUG(!addrport))
    return NULL;
  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
    if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr))
      return g;
  } SMARTLIST_FOREACH_END(g);
  return NULL;
}

/** Update the guard subsystem's knowledge of the identity of the bridge
 * at <b>addrport</b>.  Idempotent.
 */
void
entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport,
                                    const uint8_t *rsa_id_digest)
{
  guard_selection_t *gs = get_guard_selection_by_name("bridges",
                                                      GS_TYPE_BRIDGE,
                                                      0);
  if (!gs)
    return;

  entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport);
  if (!g)
    return;

  int make_persistent = 0;

  if (tor_digest_is_zero(g->identity)) {
    memcpy(g->identity, rsa_id_digest, DIGEST_LEN);
    make_persistent = 1;
  } else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) {
    /* Nothing to see here; we learned something we already knew. */
    if (BUG(! g->is_persistent))
      make_persistent = 1;
  } else {
    char old_id[HEX_DIGEST_LEN+1];
    base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity));
    log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but "
             "we already knew a different one (%s). Ignoring the new info as "
             "possibly bogus.",
             hex_str((const char *)rsa_id_digest, DIGEST_LEN),
             fmt_and_decorate_addr(&addrport->addr), addrport->port,
             old_id);
    return; // redundant, but let's be clear: we're not making this persistent.
  }

  if (make_persistent) {
    g->is_persistent = 1;
    entry_guards_changed_for_guard_selection(gs);
  }
}

/**
 * Return the number of sampled guards in <b>gs</b> that are "filtered"
 * (that is, we're willing to connect to them) and that are "usable"
 * (that is, either "reachable" or "maybe reachable").
 *
 * If a restriction is provided in <b>rst</b>, do not count any guards that
 * violate it.
 */
STATIC int
num_reachable_filtered_guards(const guard_selection_t *gs,
                              const entry_guard_restriction_t *rst)
{
  int n_reachable_filtered_guards = 0;
  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    entry_guard_consider_retry(guard);
    if (! entry_guard_obeys_restriction(guard, rst))
      continue;
    if (guard->is_usable_filtered_guard)
      ++n_reachable_filtered_guards;
  } SMARTLIST_FOREACH_END(guard);
  return n_reachable_filtered_guards;
}

/** Return the actual maximum size for the sample in <b>gs</b>,
 * given that we know about <b>n_guards</b> total. */
static int
get_max_sample_size(guard_selection_t *gs,
                    int n_guards)
{
  const int using_bridges = (gs->type == GS_TYPE_BRIDGE);
  const int min_sample = get_min_filtered_sample_size();

  /* If we are in bridge mode, expand our sample set as needed without worrying
   * about max size. We should respect the user's wishes to use many bridges if
   * that's what they have specified in their configuration file. */
  if (using_bridges)
    return INT_MAX;

  const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold());
  const int max_sample_absolute = get_max_sample_size_absolute();
  const int max_sample = MIN(max_sample_by_pct, max_sample_absolute);
  if (max_sample < min_sample)
    return min_sample;
  else
    return max_sample;
}

/**
 * Return a smartlist of the all the guards that are not currently
 * members of the sample (GUARDS - SAMPLED_GUARDS).  The elements of
 * this list are node_t pointers in the non-bridge case, and
 * bridge_info_t pointers in the bridge case.  Set *<b>n_guards_out</b>
 * to the number of guards that we found in GUARDS, including those
 * that were already sampled.
 */
static smartlist_t *
get_eligible_guards(const or_options_t *options,
                    guard_selection_t *gs,
                    int *n_guards_out)
{
  /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
  smartlist_t *eligible_guards = smartlist_new();
  int n_guards = 0; // total size of "GUARDS"

  if (gs->type == GS_TYPE_BRIDGE) {
    const smartlist_t *bridges = bridge_list_get();
    SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) {
      ++n_guards;
      if (NULL != get_sampled_guard_for_bridge(gs, bridge)) {
        continue;
      }
      smartlist_add(eligible_guards, bridge);
    } SMARTLIST_FOREACH_END(bridge);
  } else {
    const smartlist_t *nodes = nodelist_get_list();
    const int n_sampled = smartlist_len(gs->sampled_entry_guards);

    /* Build a bloom filter of our current guards: let's keep this O(N). */
    digestset_t *sampled_guard_ids = digestset_new(n_sampled);
    SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
                            guard) {
      digestset_add(sampled_guard_ids, guard->identity);
    } SMARTLIST_FOREACH_END(guard);

    SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
      if (! node_is_possible_guard(node))
        continue;
      if (gs->type == GS_TYPE_RESTRICTED) {
        /* In restricted mode, we apply the filter BEFORE sampling, so
         * that we are sampling from the nodes that we might actually
         * select. If we sampled first, we might wind up with a sample
         * that didn't include any EntryNodes at all. */
        if (! node_passes_guard_filter(options, node))
          continue;
      }
      ++n_guards;
      if (digestset_probably_contains(sampled_guard_ids, node->identity))
        continue;
      smartlist_add(eligible_guards, (node_t*)node);
    } SMARTLIST_FOREACH_END(node);

    /* Now we can free that bloom filter. */
    digestset_free(sampled_guard_ids);
  }

  *n_guards_out = n_guards;
  return eligible_guards;
}

/** Helper: given a smartlist of either bridge_info_t (if gs->type is
 * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
 * add it as a guard, remove it from the list, and return a new
 * entry_guard_t.  Return NULL on failure. */
static entry_guard_t *
select_and_add_guard_item_for_sample(guard_selection_t *gs,
                                     smartlist_t *eligible_guards)
{
  entry_guard_t *added_guard;
  if (gs->type == GS_TYPE_BRIDGE) {
    const bridge_info_t *bridge = smartlist_choose(eligible_guards);
    if (BUG(!bridge))
      return NULL; // LCOV_EXCL_LINE
    smartlist_remove(eligible_guards, bridge);
    added_guard = entry_guard_add_bridge_to_sample(gs, bridge);
  } else {
    const node_t *node =
      node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
    if (BUG(!node))
      return NULL; // LCOV_EXCL_LINE
    smartlist_remove(eligible_guards, node);
    added_guard = entry_guard_add_to_sample(gs, node);
  }

  return added_guard;
}

/**
 * Return true iff we need a consensus to update our guards, but we don't
 * have one. (We can return 0 here either if the consensus is _not_ missing,
 * or if we don't need a consensus because we're using bridges.)
 */
static int
reasonably_live_consensus_is_missing(const guard_selection_t *gs)
{
  tor_assert(gs);
  if (gs->type == GS_TYPE_BRIDGE) {
    /* We don't update bridges from the consensus; they aren't there. */
    return 0;
  }
  return networkstatus_get_reasonably_live_consensus(
                                            approx_time(),
                                            usable_consensus_flavor()) == NULL;
}

/**
 * Add new guards to the sampled guards in <b>gs</b> until there are
 * enough usable filtered guards, but never grow the sample beyond its
 * maximum size.  Return the last guard added, or NULL if none were
 * added.
 */
STATIC entry_guard_t *
entry_guards_expand_sample(guard_selection_t *gs)
{
  tor_assert(gs);
  const or_options_t *options = get_options();

  if (reasonably_live_consensus_is_missing(gs)) {
    log_info(LD_GUARD, "Not expanding the sample guard set; we have "
             "no reasonably live consensus.");
    return NULL;
  }

  int n_sampled = smartlist_len(gs->sampled_entry_guards);
  entry_guard_t *added_guard = NULL;
  int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
  int n_guards = 0;
  smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);

  const int max_sample = get_max_sample_size(gs, n_guards);
  const int min_filtered_sample = get_min_filtered_sample_size();

  log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
           "in the sample, and %d eligible guards to extend it with.",
           n_sampled, smartlist_len(eligible_guards));

  while (n_usable_filtered_guards < min_filtered_sample) {
    /* Has our sample grown too large to expand? */
    if (n_sampled >= max_sample) {
      log_info(LD_GUARD, "Not expanding the guard sample any further; "
               "just hit the maximum sample threshold of %d",
               max_sample);
      goto done;
    }

    /* Did we run out of guards? */
    if (smartlist_len(eligible_guards) == 0) {
      /* LCOV_EXCL_START
         As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
         allow all guards to be sampled, this can't be reached.
       */
      log_info(LD_GUARD, "Not expanding the guard sample any further; "
               "just ran out of eligible guards");
      goto done;
      /* LCOV_EXCL_STOP */
    }

    /* Otherwise we can add at least one new guard. */
    added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
    if (!added_guard)
      goto done; // LCOV_EXCL_LINE -- only fails on BUG.

    ++n_sampled;

    if (added_guard->is_usable_filtered_guard)
      ++n_usable_filtered_guards;
  }

 done:
  smartlist_free(eligible_guards);
  return added_guard;
}

/**
 * Helper: <b>guard</b> has just been removed from the sampled guards:
 * also remove it from primary and confirmed. */
static void
remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
                                              entry_guard_t *guard)
{
  if (guard->is_primary) {
    guard->is_primary = 0;
    smartlist_remove_keeporder(gs->primary_entry_guards, guard);
  } else {
    if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
      smartlist_remove_keeporder(gs->primary_entry_guards, guard);
    }
  }

  if (guard->confirmed_idx >= 0) {
    smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
    guard->confirmed_idx = -1;
    guard->confirmed_on_date = 0;
  } else {
    if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
      // LCOV_EXCL_START
      smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
      // LCOV_EXCL_STOP
    }
  }
}

/** Return true iff <b>guard</b> is currently "listed" -- that is, it
 * appears in the consensus, or as a configured bridge (as
 * appropriate) */
MOCK_IMPL(STATIC int,
entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
{
  if (gs->type == GS_TYPE_BRIDGE) {
    return NULL != get_bridge_info_for_guard(guard);
  } else {
    const node_t *node = node_get_by_id(guard->identity);

    return node && node_is_possible_guard(node);
  }
}

/**
 * Enumerate <b>sampled_entry_guards</b> smartlist in <b>gs</b>.
 * For each <b>entry_guard_t</b> object in smartlist, do the following:
 *  * Update <b>currently_listed</b> field to reflect if guard is listed
 *    in guard selection <b>gs</b>.
 *  * Set <b>unlisted_since_date</b> to approximate UNIX time of
 *    unlisting if guard is unlisted (randomize within 20% of
 *    get_remove_unlisted_guards_after_seconds()). Otherwise,
 *    set it to 0.
 *
 * Require <b>gs</b> to be non-null pointer.
 * Return a number of entries updated.
 */
static size_t
sampled_guards_update_consensus_presence(guard_selection_t *gs)
{
  size_t n_changes = 0;

  tor_assert(gs);

  const time_t unlisted_since_slop =
    get_remove_unlisted_guards_after_seconds() /  5;

  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    /* XXXX #20827 check ed ID too */
    const int is_listed = entry_guard_is_listed(gs, guard);

    if (is_listed && ! guard->currently_listed) {
      ++n_changes;
      guard->currently_listed = 1;
      guard->unlisted_since_date = 0;
      log_info(LD_GUARD, "Sampled guard %s is now listed again.",
               entry_guard_describe(guard));
    } else if (!is_listed && guard->currently_listed) {
      ++n_changes;
      guard->currently_listed = 0;
      guard->unlisted_since_date = randomize_time(approx_time(),
                                                  unlisted_since_slop);
      log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
               entry_guard_describe(guard));
    } else if (is_listed && guard->currently_listed) {
      log_debug(LD_GUARD, "Sampled guard %s is still listed.",
               entry_guard_describe(guard));
    } else {
      tor_assert(! is_listed && ! guard->currently_listed);
      log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
                entry_guard_describe(guard));
    }

    /* Clean up unlisted_since_date, just in case. */
    if (guard->currently_listed && guard->unlisted_since_date) {
      ++n_changes;
      guard->unlisted_since_date = 0;
      log_warn(LD_BUG, "Sampled guard %s was listed, but with "
               "unlisted_since_date set. Fixing.",
               entry_guard_describe(guard));
    } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
      ++n_changes;
      guard->unlisted_since_date = randomize_time(approx_time(),
                                                  unlisted_since_slop);
      log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
               "unlisted_since_date unset. Fixing.",
               entry_guard_describe(guard));
    }
  } SMARTLIST_FOREACH_END(guard);

  return n_changes;
}

/**
 * Enumerate <b>sampled_entry_guards</b> smartlist in <b>gs</b>.
 * For each <b>entry_guard_t</b> object in smartlist, do the following:
 * * If <b>currently_listed</b> is false and <b>unlisted_since_date</b>
 *   is earlier than <b>remove_if_unlisted_since</b> - remove it.
 * * Otherwise, check if <b>sampled_on_date</b> is earlier than
 *   <b>maybe_remove_if_sampled_before</b>.
 *   * When above condition is correct, remove the guard if:
 *     * It was never confirmed.
 *     * It was confirmed before <b>remove_if_confirmed_before</b>.
 *
 * Require <b>gs</b> to be non-null pointer.
 * Return number of entries deleted.
 */
static size_t
sampled_guards_prune_obsolete_entries(guard_selection_t *gs,
                                  const time_t remove_if_unlisted_since,
                                  const time_t maybe_remove_if_sampled_before,
                                  const time_t remove_if_confirmed_before)
{
  size_t n_changes = 0;

  tor_assert(gs);

  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    int rmv = 0;

    if (guard->currently_listed == 0 &&
        guard->unlisted_since_date < remove_if_unlisted_since) {
      /*
        "We have a live consensus, and {IS_LISTED} is false, and
         {FIRST_UNLISTED_AT} is over get_remove_unlisted_guards_after_days()
         days in the past."
      */
      log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
               "for over %d days", entry_guard_describe(guard),
               get_remove_unlisted_guards_after_days());
      rmv = 1;
    } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
      /* We have a live consensus, and {ADDED_ON_DATE} is over
        {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
        "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
      */
      if (guard->confirmed_on_date == 0) {
        rmv = 1;
        log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
                 "over %d days ago, but never confirmed.",
                 entry_guard_describe(guard),
                 get_guard_lifetime() / 86400);
      } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
        rmv = 1;
        log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
                 "over %d days ago, and confirmed over %d days ago.",
                 entry_guard_describe(guard),
                 get_guard_lifetime() / 86400,
                 get_guard_confirmed_min_lifetime() / 86400);
      }
    }

    if (rmv) {
      ++n_changes;
      SMARTLIST_DEL_CURRENT_KEEPORDER(gs->sampled_entry_guards, guard);
      remove_guard_from_confirmed_and_primary_lists(gs, guard);
      entry_guard_free(guard);
    }
  } SMARTLIST_FOREACH_END(guard);

  return n_changes;
}

/**
 * Update the status of all sampled guards based on the arrival of a
 * new consensus networkstatus document.  This will include marking
 * some guards as listed or unlisted, and removing expired guards. */
STATIC void
sampled_guards_update_from_consensus(guard_selection_t *gs)
{
  tor_assert(gs);

  // It's important to use a reasonably live consensus here; we want clients
  // to bootstrap even if their clock is skewed by more than 2-3 hours.
  // But we don't want to make changes based on anything that's really old.
  if (reasonably_live_consensus_is_missing(gs)) {
    log_info(LD_GUARD, "Not updating the sample guard set; we have "
             "no reasonably live consensus.");
    return;
  }
  log_info(LD_GUARD, "Updating sampled guard status based on received "
           "consensus.");

  /* First: Update listed/unlisted. */
  size_t n_changes = sampled_guards_update_consensus_presence(gs);

  const time_t remove_if_unlisted_since =
    approx_time() - get_remove_unlisted_guards_after_seconds();
  const time_t maybe_remove_if_sampled_before =
    approx_time() - get_guard_lifetime();
  const time_t remove_if_confirmed_before =
    approx_time() - get_guard_confirmed_min_lifetime();

  /* Then: remove the ones that have been junk for too long */
  n_changes +=
    sampled_guards_prune_obsolete_entries(gs,
                                          remove_if_unlisted_since,
                                          maybe_remove_if_sampled_before,
                                          remove_if_confirmed_before);

  if (n_changes) {
    gs->primary_guards_up_to_date = 0;
    entry_guards_update_filtered_sets(gs);
    /* We don't need to rebuild the confirmed list right here -- we may have
     * removed confirmed guards above, but we can't have added any new
     * confirmed guards.
     */
    entry_guards_changed_for_guard_selection(gs);
  }
}

/**
 * Return true iff <b>node</b> is a Tor relay that we are configured to
 * be able to connect to. */
static int
node_passes_guard_filter(const or_options_t *options,
                         const node_t *node)
{
  /* NOTE: Make sure that this function stays in sync with
   * options_transition_affects_entry_guards */
  if (routerset_contains_node(options->ExcludeNodes, node))
    return 0;

  if (options->EntryNodes &&
      !routerset_contains_node(options->EntryNodes, node))
    return 0;

  if (!reachable_addr_allows_node(node, FIREWALL_OR_CONNECTION, 0))
    return 0;

  if (node_is_a_configured_bridge(node))
    return 0;

  return 1;
}

/** Helper: Return true iff <b>bridge</b> passes our configuration
 * filter-- if it is a relay that we are configured to be able to
 * connect to. */
static int
bridge_passes_guard_filter(const or_options_t *options,
                           const bridge_info_t *bridge)
{
  tor_assert(bridge);
  if (!bridge)
    return 0;

  if (routerset_contains_bridge(options->ExcludeNodes, bridge))
    return 0;

  /* Ignore entrynodes */
  const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);

  if (!reachable_addr_allows_addr(&addrport->addr,
                                            addrport->port,
                                            FIREWALL_OR_CONNECTION,
                                            0, 0))
    return 0;

  return 1;
}

/**
 * Return true iff <b>guard</b> is a Tor relay that we are configured to
 * be able to connect to, and we haven't disabled it for omission from
 * the consensus or path bias issues. */
static int
entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
                          entry_guard_t *guard)
{
  if (guard->currently_listed == 0)
    return 0;
  if (guard->pb.path_bias_disabled)
    return 0;

  if (gs->type == GS_TYPE_BRIDGE) {
    const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
    if (bridge == NULL)
      return 0;
    return bridge_passes_guard_filter(options, bridge);
  } else {
    const node_t *node = node_get_by_id(guard->identity);
    if (node == NULL) {
      // This can happen when currently_listed is true, and we're not updating
      // it because we don't have a live consensus.
      return 0;
    }

    return node_passes_guard_filter(options, node);
  }
}

/** Return true iff <b>guard</b> is in the same family as <b>node</b>.
 */
static int
guard_in_node_family(const entry_guard_t *guard, const node_t *node)
{
  const node_t *guard_node = node_get_by_id(guard->identity);
  if (guard_node) {
    return nodes_in_same_family(guard_node, node);
  } else {
    /* If we don't have a node_t for the guard node, we might have
     * a bridge_info_t for it. So let's check to see whether the bridge
     * address matches has any family issues.
     *
     * (Strictly speaking, I believe this check is unnecessary, since we only
     * use it to avoid the exit's family when building circuits, and we don't
     * build multihop circuits until we have a routerinfo_t for the
     * bridge... at which point, we'll also have a node_t for the
     * bridge. Nonetheless, it seems wise to include it, in case our
     * assumptions change down the road.  -nickm.)
     */
    if (get_options()->EnforceDistinctSubnets && guard->bridge_addr) {
      tor_addr_t node_addr;
      node_get_addr(node, &node_addr);
      if (router_addrs_in_same_network(&node_addr,
                                       &guard->bridge_addr->addr)) {
        return 1;
      }
    }
    return 0;
  }
}

/* Allocate and return a new exit guard restriction (where <b>exit_id</b> is of
 * size DIGEST_LEN) */
STATIC entry_guard_restriction_t *
guard_create_exit_restriction(const uint8_t *exit_id)
{
  entry_guard_restriction_t *rst = NULL;
  rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
  rst->type = RST_EXIT_NODE;
  memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
  return rst;
}

/** If we have fewer than this many possible usable guards, don't set
 * MD-availability-based restrictions: we might denylist all of them. */
#define MIN_GUARDS_FOR_MD_RESTRICTION 10

/** Return true if we should set md dirserver restrictions. We might not want
 *  to set those if our guard options are too restricted, since we don't want
 *  to denylist all of them. */
static int
should_set_md_dirserver_restriction(void)
{
  const guard_selection_t *gs = get_guard_selection_info();
  int num_usable_guards = num_reachable_filtered_guards(gs, NULL);

  /* Don't set restriction if too few reachable filtered guards. */
  if (num_usable_guards < MIN_GUARDS_FOR_MD_RESTRICTION) {
    log_info(LD_GUARD, "Not setting md restriction: only %d"
             " usable guards.", num_usable_guards);
    return 0;
  }

  /* We have enough usable guards: set MD restriction */
  return 1;
}

/** Allocate and return an outdated md guard restriction. Return NULL if no
 *  such restriction is needed. */
STATIC entry_guard_restriction_t *
guard_create_dirserver_md_restriction(void)
{
  entry_guard_restriction_t *rst = NULL;

  if (!should_set_md_dirserver_restriction()) {
    log_debug(LD_GUARD, "Not setting md restriction: too few "
              "filtered guards.");
    return NULL;
  }

  rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
  rst->type = RST_OUTDATED_MD_DIRSERVER;

  return rst;
}

/* Return True if <b>guard</b> obeys the exit restriction <b>rst</b>. */
static int
guard_obeys_exit_restriction(const entry_guard_t *guard,
                             const entry_guard_restriction_t *rst)
{
  tor_assert(rst->type == RST_EXIT_NODE);

  // Exclude the exit ID and all of its family.
  const node_t *node = node_get_by_id((const char*)rst->exclude_id);
  if (node && guard_in_node_family(guard, node))
    return 0;

  return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
}

/** Return True if <b>guard</b> should be used as a dirserver for fetching
 *  microdescriptors. */
static int
guard_obeys_md_dirserver_restriction(const entry_guard_t *guard)
{
  /* If this guard is an outdated dirserver, don't use it. */
  if (microdesc_relay_is_outdated_dirserver(guard->identity)) {
    log_info(LD_GENERAL, "Skipping %s dirserver: outdated",
             hex_str(guard->identity, DIGEST_LEN));
    return 0;
  }

  log_debug(LD_GENERAL, "%s dirserver obeys md restrictions",
            hex_str(guard->identity, DIGEST_LEN));

  return 1;
}

/**
 * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
 * (If <b>rst</b> is NULL, there are no restrictions.)
 */
static int
entry_guard_obeys_restriction(const entry_guard_t *guard,
                              const entry_guard_restriction_t *rst)
{
  tor_assert(guard);
  if (! rst)
    return 1; // No restriction?  No problem.

  if (rst->type == RST_EXIT_NODE) {
    return guard_obeys_exit_restriction(guard, rst);
  } else if (rst->type == RST_OUTDATED_MD_DIRSERVER) {
    return guard_obeys_md_dirserver_restriction(guard);
  }

  tor_assert_nonfatal_unreached();
  return 0;
}

/**
 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
 * flags on <b>guard</b>. */
void
entry_guard_set_filtered_flags(const or_options_t *options,
                               guard_selection_t *gs,
                               entry_guard_t *guard)
{
  unsigned was_filtered = guard->is_filtered_guard;
  guard->is_filtered_guard = 0;
  guard->is_usable_filtered_guard = 0;

  if (entry_guard_passes_filter(options, gs, guard)) {
    guard->is_filtered_guard = 1;

    if (guard->is_reachable != GUARD_REACHABLE_NO)
      guard->is_usable_filtered_guard = 1;

    entry_guard_consider_retry(guard);
  }
  log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
            "reachable_filtered=%d.", entry_guard_describe(guard),
            guard->is_filtered_guard, guard->is_usable_filtered_guard);

  if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
    /* This guard might now be primary or nonprimary. */
    gs->primary_guards_up_to_date = 0;
  }
}

/**
 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
 * flag on every guard in <b>gs</b>. */
STATIC void
entry_guards_update_filtered_sets(guard_selection_t *gs)
{
  const or_options_t *options = get_options();

  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    entry_guard_set_filtered_flags(options, gs, guard);
  } SMARTLIST_FOREACH_END(guard);
}

/**
 * Return the first sampled guard from the reachable filtered sample guards
 * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
 * Return NULL if no such guard can be found.
 *
 * Make sure that the sample is big enough, and that all the filter flags
 * are set correctly, before calling this function.
 *
 * If a restriction is provided in <b>rst</b>, do not return any guards that
 * violate it.
 **/
STATIC entry_guard_t *
first_reachable_filtered_entry_guard(guard_selection_t *gs,
                                       const entry_guard_restriction_t *rst,
                                       unsigned flags)
{
  tor_assert(gs);
  entry_guard_t *result = NULL;
  const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
  const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
  const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
  const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
  const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;

  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    entry_guard_consider_retry(guard);
  } SMARTLIST_FOREACH_END(guard);

  const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);

  log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
           "in the USABLE_FILTERED set.", n_reachable_filtered);

  const int min_filtered_sample = get_min_filtered_sample_size();
  if (n_reachable_filtered < min_filtered_sample) {
    log_info(LD_GUARD, "  (That isn't enough. Trying to expand the sample.)");
    entry_guards_expand_sample(gs);
  }

  if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
    entry_guards_update_primary(gs);

  /* Build the set of reachable filtered guards. */
  smartlist_t *reachable_filtered_sample = smartlist_new();
  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    entry_guard_consider_retry(guard);// redundant, but cheap.
    if (! entry_guard_obeys_restriction(guard, rst))
      continue;
    if (! guard->is_usable_filtered_guard)
      continue;
    if (exclude_confirmed && guard->confirmed_idx >= 0)
      continue;
    if (exclude_primary && guard->is_primary)
      continue;
    if (exclude_pending && guard->is_pending)
      continue;
    if (need_descriptor && !guard_has_descriptor(guard))
      continue;
    smartlist_add(reachable_filtered_sample, guard);
  } SMARTLIST_FOREACH_END(guard);

  log_info(LD_GUARD, "  (After filters [%x], we have %d guards to consider.)",
           flags, smartlist_len(reachable_filtered_sample));

  if (smartlist_len(reachable_filtered_sample)) {
    /**
     * Get the first guard of the filtered set builds from
     * sampled_entry_guards. Proposal 310 suggests this design to overcome
     * performance and security issues linked to the previous selection
     * method. The guard selected here should be filtered out if this function
     * is called again in the same context. I.e., if we filter guards to add
     * them into some list X, then the guards from list X will be filtered out
     * when this function is called again. Hence it requires setting exclude
     * flags in a appropriate way (depending of the context of the caller).
     */
    result = smartlist_get(reachable_filtered_sample, 0);
    log_info(LD_GUARD, "  (Selected %s.)",
             result ? entry_guard_describe(result) : "<null>");
  }
  smartlist_free(reachable_filtered_sample);

  return result;
}

static int
compare_guards_by_confirmed_idx(const void **a_, const void **b_)
{
  const entry_guard_t *a = *a_, *b = *b_;
  if (a->confirmed_idx < b->confirmed_idx)
    return -1;
  else if (a->confirmed_idx > b->confirmed_idx)
    return 1;
  else
    return 0;
}
/**
 * Helper: compare two entry_guard_t by their sampled_idx values.
 * Used to sort the sampled list
 */
static int
compare_guards_by_sampled_idx(const void **a_, const void **b_)
{
  const entry_guard_t *a = *a_, *b = *b_;
  if (a->sampled_idx < b->sampled_idx)
    return -1;
  else if (a->sampled_idx > b->sampled_idx)
    return 1;
  else
    return 0;
}

/**
 * Find the confirmed guards from among the sampled guards in <b>gs</b>,
 * and put them in confirmed_entry_guards in the correct
 * order. Recalculate their indices.
 */
STATIC void
entry_guards_update_confirmed(guard_selection_t *gs)
{
  smartlist_clear(gs->confirmed_entry_guards);
  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    if (guard->confirmed_idx >= 0)
      smartlist_add(gs->confirmed_entry_guards, guard);
  } SMARTLIST_FOREACH_END(guard);

  smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
  /** Needed to keep a dense array of confirmed_idx */
  int any_changed = 0;
  SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
    if (guard->confirmed_idx != guard_sl_idx) {
      any_changed = 1;
      guard->confirmed_idx = guard_sl_idx;
    }
  } SMARTLIST_FOREACH_END(guard);

  gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
  // We need the confirmed list to always be give guards in sampled order
  smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_sampled_idx);

  if (any_changed) {
    entry_guards_changed_for_guard_selection(gs);
  }
}

/**
 * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
 * connected to, and intend to use again.
 */
STATIC void
make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
{
  if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
    return; // LCOV_EXCL_LINE

  if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
    return; // LCOV_EXCL_LINE

  const int GUARD_LIFETIME = get_guard_lifetime();
  guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);

  log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
           entry_guard_describe(guard),
           gs->next_confirmed_idx);

  guard->confirmed_idx = gs->next_confirmed_idx++;
  smartlist_add(gs->confirmed_entry_guards, guard);
  /** The confirmation ordering might not be the sample ording. We need to
   * reorder */
  smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_sampled_idx);

  // This confirmed guard might kick something else out of the primary
  // guards.
  gs->primary_guards_up_to_date = 0;

  entry_guards_changed_for_guard_selection(gs);
}

/**
 * Recalculate the list of primary guards (the ones we'd prefer to use) from
 * the filtered sample and the confirmed list.
 */
STATIC void
entry_guards_update_primary(guard_selection_t *gs)
{
  tor_assert(gs);

  // prevent recursion. Recursion is potentially very bad here.
  static int running = 0;
  tor_assert(!running);
  running = 1;

  const int N_PRIMARY_GUARDS = get_n_primary_guards();

  smartlist_t *new_primary_guards = smartlist_new();
  smartlist_t *old_primary_guards = smartlist_new();
  smartlist_add_all(old_primary_guards, gs->primary_entry_guards);

  /* Set this flag now, to prevent the calls below from recursing. */
  gs->primary_guards_up_to_date = 1;

  /* First, can we fill it up with confirmed guards? */
  SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
    if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
      break;
    if (! guard->is_filtered_guard)
      continue;
    guard->is_primary = 1;
    smartlist_add(new_primary_guards, guard);
  } SMARTLIST_FOREACH_END(guard);

  SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
    /* Can we keep any older primary guards? First remove all the ones
     * that we already kept. */
    if (smartlist_contains(new_primary_guards, guard)) {
      SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
      continue;
    }

    /* Now add any that are still good. */
    if (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS &&
        guard->is_filtered_guard) {
      guard->is_primary = 1;
      smartlist_add(new_primary_guards, guard);
      SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
    } else {
      /* Mark the remaining previous primary guards as non-primary */
      guard->is_primary = 0;
    }
  } SMARTLIST_FOREACH_END(guard);

  /* Finally, fill out the list with sampled guards. */
  while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
    entry_guard_t *guard = first_reachable_filtered_entry_guard(gs, NULL,
                                            SAMPLE_EXCLUDE_CONFIRMED|
                                            SAMPLE_EXCLUDE_PRIMARY|
                                            SAMPLE_NO_UPDATE_PRIMARY);
    if (!guard)
      break;
    guard->is_primary = 1;
    smartlist_add(new_primary_guards, guard);
  }

#if 1
  /* Debugging. */
  SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
    tor_assert_nonfatal(
                   bool_eq(guard->is_primary,
                           smartlist_contains(new_primary_guards, guard)));
  });
#endif /* 1 */

  const int any_change = !smartlist_ptrs_eq(gs->primary_entry_guards,
                                            new_primary_guards);
  if (any_change) {
    log_info(LD_GUARD, "Primary entry guards have changed. "
             "New primary guard list is: ");
    int n = smartlist_len(new_primary_guards);
    SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
      log_info(LD_GUARD, "  %d/%d: %s%s%s",
               g_sl_idx+1, n, entry_guard_describe(g),
               g->confirmed_idx >= 0 ? " (confirmed)" : "",
               g->is_filtered_guard ? "" : " (excluded by filter)");
    } SMARTLIST_FOREACH_END(g);
    smartlist_sort(new_primary_guards, compare_guards_by_sampled_idx);
  }

  smartlist_free(old_primary_guards);
  smartlist_free(gs->primary_entry_guards);
  gs->primary_entry_guards = new_primary_guards;
  gs->primary_guards_up_to_date = 1;
  running = 0;
}

/**
 * Return the number of seconds after the last attempt at which we should
 * retry a guard that has been failing since <b>failing_since</b>.
 */
static int
get_retry_schedule(time_t failing_since, time_t now,
                   int is_primary)
{
  const unsigned SIX_HOURS = 6 * 3600;
  const unsigned FOUR_DAYS = 4 * 86400;
  const unsigned SEVEN_DAYS = 7 * 86400;

  time_t tdiff;
  if (now > failing_since) {
    tdiff = now - failing_since;
  } else {
    tdiff = 0;
  }

  const struct {
    time_t maximum; int primary_delay; int nonprimary_delay;
  } delays[] = {
    // clang-format off
    { SIX_HOURS,    10*60,  1*60*60 },
    { FOUR_DAYS,    90*60,  4*60*60 },
    { SEVEN_DAYS, 4*60*60, 18*60*60 },
    { TIME_MAX,   9*60*60, 36*60*60 }
    // clang-format on
  };

  unsigned i;
  for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
    if (tdiff <= delays[i].maximum) {
      return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
    }
  }
  /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
  tor_assert_nonfatal_unreached();
  return 36*60*60;
  /* LCOV_EXCL_STOP */
}

/**
 * If <b>guard</b> is unreachable, consider whether enough time has passed
 * to consider it maybe-reachable again.
 */
STATIC void
entry_guard_consider_retry(entry_guard_t *guard)
{
  if (guard->is_reachable != GUARD_REACHABLE_NO)
    return; /* No retry needed. */

  const time_t now = approx_time();
  const int delay =
    get_retry_schedule(guard->failing_since, now, guard->is_primary);
  const time_t last_attempt = guard->last_tried_to_connect;

  /* Check if it is a bridge and we don't have its descriptor yet */
  if (guard->bridge_addr && !guard_has_descriptor(guard)) {
    /* We want to leave the retry schedule to fetch_bridge_descriptors(),
     * so we don't have two retry schedules clobbering each other. See
     * bugs 40396 and 40497 for details of why we need this exception. */
    return;
  }

  if (BUG(last_attempt == 0) ||
      now >= last_attempt + delay) {
    /* We should mark this retriable. */
    char tbuf[ISO_TIME_LEN+1];
    format_local_iso_time(tbuf, last_attempt);
    log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
             "haven't tried to use it since %s.",
             guard->is_primary?"primary ":"",
             guard->confirmed_idx>=0?"confirmed ":"",
             entry_guard_describe(guard),
             tbuf);

    guard->is_reachable = GUARD_REACHABLE_MAYBE;
    if (guard->is_filtered_guard)
      guard->is_usable_filtered_guard = 1;
  }
}

/** Tell the entry guards subsystem that we have confirmed that as of
 * just now, we're on the internet. */
void
entry_guards_note_internet_connectivity(guard_selection_t *gs)
{
  gs->last_time_on_internet = approx_time();
}

/**
 * Pick a primary guard for use with a circuit, if available. Update the
 * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
 * guard as appropriate.  Set <b>state_out</b> to the new guard-state
 * of the circuit.
 */
static entry_guard_t *
select_primary_guard_for_circuit(guard_selection_t *gs,
                                 guard_usage_t usage,
                                 const entry_guard_restriction_t *rst,
                                 unsigned *state_out)
{
  const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
  entry_guard_t *chosen_guard = NULL;

  int num_entry_guards = get_n_primary_guards_to_use(usage);
  smartlist_t *usable_primary_guards = smartlist_new();

  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
    entry_guard_consider_retry(guard);
    if (!entry_guard_obeys_restriction(guard, rst)) {
      log_info(LD_GUARD, "Entry guard %s doesn't obey restriction, we test the"
          " next one", entry_guard_describe(guard));
      continue;
    }
    if (guard->is_reachable != GUARD_REACHABLE_NO) {
      if (need_descriptor && !guard_has_descriptor(guard)) {
        log_info(LD_GUARD, "Guard %s does not have a descriptor",
            entry_guard_describe(guard));
        continue;
      }
      *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
      guard->last_tried_to_connect = approx_time();
      smartlist_add(usable_primary_guards, guard);
      if (smartlist_len(usable_primary_guards) >= num_entry_guards)
        break;
    }
  } SMARTLIST_FOREACH_END(guard);

  if (smartlist_len(usable_primary_guards)) {
    chosen_guard = smartlist_choose(usable_primary_guards);
    log_info(LD_GUARD,
        "Selected primary guard %s for circuit from a list size of %d.",
        entry_guard_describe(chosen_guard),
        smartlist_len(usable_primary_guards));
    smartlist_free(usable_primary_guards);
  }

  smartlist_free(usable_primary_guards);
  return chosen_guard;
}

/**
 * For use with a circuit, pick a non-pending running filtered confirmed guard,
 * if one is available. Update the <b>last_tried_to_connect</b> time and the
 * <b>is_pending</b> fields of the guard as appropriate. Set <b>state_out</b>
 * to the new guard-state of the circuit.
 */
static entry_guard_t *
select_confirmed_guard_for_circuit(guard_selection_t *gs,
                                  guard_usage_t usage,
                                  const entry_guard_restriction_t *rst,
                                  unsigned *state_out)
{
  const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);

  SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
    if (guard->is_primary)
      continue; /* we already considered this one. */
    if (! entry_guard_obeys_restriction(guard, rst))
      continue;
    entry_guard_consider_retry(guard);
    if (guard->is_usable_filtered_guard && ! guard->is_pending) {
      if (need_descriptor && !guard_has_descriptor(guard))
        continue; /* not a bug */
      guard->is_pending = 1;
      guard->last_tried_to_connect = approx_time();
      *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
      log_info(LD_GUARD, "No primary guards available. Selected confirmed "
               "guard %s for circuit. Will try other guards before using "
               "this circuit.",
               entry_guard_describe(guard));
      return guard;
    }
  } SMARTLIST_FOREACH_END(guard);

  return NULL;
}

/**
 * For use with a circuit, pick a usable filtered guard. Update the
 * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
 * guard as appropriate. Set <b>state_out</b> to the new guard-state of the
 * circuit.
 */
static entry_guard_t *
select_filtered_guard_for_circuit(guard_selection_t *gs,
                                  guard_usage_t usage,
                                  const entry_guard_restriction_t *rst,
                                  unsigned *state_out)
{
  const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
  entry_guard_t *chosen_guard = NULL;
  unsigned flags = 0;
  if (need_descriptor)
    flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
  chosen_guard = first_reachable_filtered_entry_guard(gs,
                                                 rst,
                                                 SAMPLE_EXCLUDE_CONFIRMED |
                                                 SAMPLE_EXCLUDE_PRIMARY |
                                                 SAMPLE_EXCLUDE_PENDING |
                                                 flags);
  if (!chosen_guard) {
    return NULL;
  }

  chosen_guard->is_pending = 1;
  chosen_guard->last_tried_to_connect = approx_time();
  *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
  log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
           "guard %s for circuit. Will try other guards before "
           "using this circuit.",
           entry_guard_describe(chosen_guard));
  return chosen_guard;
}

/**
 * Get a guard for use with a circuit.  Prefer to pick a running primary
 * guard; then a non-pending running filtered confirmed guard; then a
 * non-pending runnable filtered guard.  Update the
 * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
 * guard as appropriate.  Set <b>state_out</b> to the new guard-state
 * of the circuit.
 */
STATIC entry_guard_t *
select_entry_guard_for_circuit(guard_selection_t *gs,
                               guard_usage_t usage,
                               const entry_guard_restriction_t *rst,
                               unsigned *state_out)
{
  entry_guard_t *chosen_guard = NULL;
  tor_assert(gs);
  tor_assert(state_out);

  if (!gs->primary_guards_up_to_date)
    entry_guards_update_primary(gs);

  /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
      <maybe> or <yes>, return the first such guard." */
  chosen_guard = select_primary_guard_for_circuit(gs, usage, rst, state_out);
  if (chosen_guard)
    return chosen_guard;

  /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
      and {USABLE_FILTERED_GUARDS} is nonempty, return the first
      entry in that intersection that has {is_pending} set to
      false." */
  chosen_guard = select_confirmed_guard_for_circuit(gs, usage, rst, state_out);
  if (chosen_guard)
    return chosen_guard;

  /* "Otherwise, if there is no such entry, select a member
   * {USABLE_FILTERED_GUARDS} following the sample ordering" */
  chosen_guard = select_filtered_guard_for_circuit(gs, usage, rst, state_out);

  if (chosen_guard == NULL) {
    log_info(LD_GUARD, "Absolutely no sampled guards were available. "
             "Marking all guards for retry and starting from top again.");
    mark_all_guards_maybe_reachable(gs);
    return NULL;
  }

  return chosen_guard;
}

/**
 * Note that we failed to connect to or build circuits through <b>guard</b>.
 * Use with a guard returned by select_entry_guard_for_circuit().
 */
STATIC void
entry_guards_note_guard_failure(guard_selection_t *gs,
                                entry_guard_t *guard)
{
  tor_assert(gs);

  guard->is_reachable = GUARD_REACHABLE_NO;
  guard->is_usable_filtered_guard = 0;

  guard->is_pending = 0;
  if (guard->failing_since == 0)
    guard->failing_since = approx_time();

  /* This guard not reachable: send GUARD DOWN event */
  control_event_guard(guard->nickname, guard->identity, "DOWN");

  log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
           guard->is_primary?"primary ":"",
           guard->confirmed_idx>=0?"confirmed ":"",
           entry_guard_describe(guard));

  /* Schedule a re-assessment of whether we have enough dir info to
   * use the network. Counterintuitively, *losing* a bridge might actually
   * be just what we need to *resume* using the network, if we had it in
   * state GUARD_REACHABLE_MAYBE and we were stalling to learn this
   * outcome. See bug 40396 for more details. */
  router_dir_info_changed();
}

/**
 * Note that we successfully connected to, and built a circuit through
 * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
 * return the new guard-state of the circuit.
 *
 * Be aware: the circuit is only usable when its guard-state becomes
 * GUARD_CIRC_STATE_COMPLETE.
 **/
STATIC unsigned
entry_guards_note_guard_success(guard_selection_t *gs,
                                entry_guard_t *guard,
                                unsigned old_state)
{
  tor_assert(gs);

  /* Save this, since we're about to overwrite it. */
  const time_t last_time_on_internet = gs->last_time_on_internet;
  gs->last_time_on_internet = approx_time();

  /* If guard was not already marked as reachable, send a GUARD UP signal */
  if (guard->is_reachable != GUARD_REACHABLE_YES) {
    control_event_guard(guard->nickname, guard->identity, "UP");

    /* Schedule a re-assessment of whether we have enough dir info to
     * use the network. One of our guards has just moved to
     * GUARD_REACHABLE_YES, so maybe we can resume using the network
     * now. */
    router_dir_info_changed();
  }

  guard->is_reachable = GUARD_REACHABLE_YES;
  guard->failing_since = 0;
  guard->is_pending = 0;
  if (guard->is_filtered_guard)
    guard->is_usable_filtered_guard = 1;

  if (guard->confirmed_idx < 0) {
    make_guard_confirmed(gs, guard);
    if (!gs->primary_guards_up_to_date)
      entry_guards_update_primary(gs);
  }

  unsigned new_state;
  switch (old_state) {
    case GUARD_CIRC_STATE_COMPLETE:
    case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
      new_state = GUARD_CIRC_STATE_COMPLETE;
      break;
    default:
      tor_assert_nonfatal_unreached();
      FALLTHROUGH_UNLESS_ALL_BUGS_ARE_FATAL;
    case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
      if (guard->is_primary) {
        /* XXXX #20832 -- I don't actually like this logic. It seems to make
         * us a little more susceptible to evil-ISP attacks.  The mitigations
         * I'm thinking of, however, aren't local to this point, so I'll leave
         * it alone. */
        /* This guard may have become primary by virtue of being confirmed.
         * If so, the circuit for it is now complete.
         */
        new_state = GUARD_CIRC_STATE_COMPLETE;
      } else {
        new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
      }
      break;
  }

  if (! guard->is_primary) {
    if (last_time_on_internet + get_internet_likely_down_interval()
        < approx_time()) {
      mark_primary_guards_maybe_reachable(gs);
    }
  }

  log_info(LD_GUARD, "Recorded success for %s%sguard %s",
           guard->is_primary?"primary ":"",
           guard->confirmed_idx>=0?"confirmed ":"",
           entry_guard_describe(guard));

  return new_state;
}

/**
 * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
 */
STATIC int
entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
{
  tor_assert(a && b);
  if (a == b)
    return 0;

  /* Confirmed is always better than unconfirmed; lower index better
     than higher */
  if (a->confirmed_idx < 0) {
    if (b->confirmed_idx >= 0)
      return 0;
  } else {
    if (b->confirmed_idx < 0)
      return 1;

    /* Lower confirmed_idx is better than higher. */
    return (a->confirmed_idx < b->confirmed_idx);
  }

  /* If we reach this point, both are unconfirmed. If one is pending, it
   * has higher priority. */
  if (a->is_pending) {
    if (! b->is_pending)
      return 1;

    /* Both are pending: earlier last_tried_connect wins. */
    return a->last_tried_to_connect < b->last_tried_to_connect;
  } else {
    if (b->is_pending)
      return 0;

    /* Neither is pending: priorities are equal. */
    return 0;
  }
}

/** Release all storage held in <b>restriction</b> */
STATIC void
entry_guard_restriction_free_(entry_guard_restriction_t *rst)
{
  tor_free(rst);
}

/**
 * Release all storage held in <b>state</b>.
 */
void
circuit_guard_state_free_(circuit_guard_state_t *state)
{
  if (!state)
    return;
  entry_guard_restriction_free(state->restrictions);
  entry_guard_handle_free(state->guard);
  tor_free(state);
}

/** Allocate and return a new circuit_guard_state_t to track the result
 * of using <b>guard</b> for a given operation. */
MOCK_IMPL(STATIC circuit_guard_state_t *,
circuit_guard_state_new,(entry_guard_t *guard, unsigned state,
                         entry_guard_restriction_t *rst))
{
  circuit_guard_state_t *result;

  result = tor_malloc_zero(sizeof(circuit_guard_state_t));
  result->guard = entry_guard_handle_new(guard);
  result->state = state;
  result->state_set_at = approx_time();
  result->restrictions = rst;

  return result;
}

/**
 * Pick a suitable entry guard for a circuit in, and place that guard
 * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
 * state object that will record whether the circuit is ready to be used
 * or not. Return 0 on success; on failure, return -1.
 *
 * If a restriction is provided in <b>rst</b>, do not return any guards that
 * violate it, and remember that restriction in <b>guard_state_out</b> for
 * later use. (Takes ownership of the <b>rst</b> object.)
 */
int
entry_guard_pick_for_circuit(guard_selection_t *gs,
                             guard_usage_t usage,
                             entry_guard_restriction_t *rst,
                             const node_t **chosen_node_out,
                             circuit_guard_state_t **guard_state_out)
{
  tor_assert(gs);
  tor_assert(chosen_node_out);
  tor_assert(guard_state_out);
  *chosen_node_out = NULL;
  *guard_state_out = NULL;

  unsigned state = 0;
  entry_guard_t *guard =
    select_entry_guard_for_circuit(gs, usage, rst, &state);
  if (! guard)
    goto fail;
  if (BUG(state == 0))
    goto fail;
  const node_t *node = node_get_by_id(guard->identity);
  // XXXX #20827 check Ed ID.
  if (! node)
    goto fail;
  if (BUG(usage != GUARD_USAGE_DIRGUARD &&
          !node_has_preferred_descriptor(node, 1)))
    goto fail;

  *chosen_node_out = node;
  *guard_state_out = circuit_guard_state_new(guard, state, rst);

  return 0;
 fail:
  entry_guard_restriction_free(rst);
  return -1;
}

/**
 * Called by the circuit building module when a circuit has succeeded: informs
 * the guards code that the guard in *<b>guard_state_p</b> is working, and
 * advances the state of the guard module.  On a GUARD_USABLE_NEVER return
 * value, the circuit is broken and should not be used.  On a GUARD_USABLE_NOW
 * return value, the circuit is ready to use.  On a GUARD_MAYBE_USABLE_LATER
 * return value, the circuit should not be used until we find out whether
 * preferred guards will work for us.
 */
guard_usable_t
entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
{
  if (BUG(*guard_state_p == NULL))
    return GUARD_USABLE_NEVER;

  entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  if (! guard || BUG(guard->in_selection == NULL))
    return GUARD_USABLE_NEVER;

  unsigned newstate =
    entry_guards_note_guard_success(guard->in_selection, guard,
                                    (*guard_state_p)->state);

  (*guard_state_p)->state = newstate;
  (*guard_state_p)->state_set_at = approx_time();

  if (newstate == GUARD_CIRC_STATE_COMPLETE) {
    return GUARD_USABLE_NOW;
  } else {
    return GUARD_MAYBE_USABLE_LATER;
  }
}

/** Cancel the selection of *<b>guard_state_p</b> without declaring
 * success or failure. It is safe to call this function if success or
 * failure _has_ already been declared. */
void
entry_guard_cancel(circuit_guard_state_t **guard_state_p)
{
  if (BUG(*guard_state_p == NULL))
    return;
  entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  if (! guard)
    return;

  /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
   * function will only get called in "bug" cases anyway. */
  guard->is_pending = 0;
  circuit_guard_state_free(*guard_state_p);
  *guard_state_p = NULL;
}

/**
 * Called by the circuit building module when a circuit has failed:
 * informs the guards code that the guard in *<b>guard_state_p</b> is
 * not working, and advances the state of the guard module.
 */
void
entry_guard_failed(circuit_guard_state_t **guard_state_p)
{
  if (BUG(*guard_state_p == NULL))
    return;

  entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
  if (! guard || BUG(guard->in_selection == NULL))
    return;

  entry_guards_note_guard_failure(guard->in_selection, guard);

  (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
  (*guard_state_p)->state_set_at = approx_time();
}

/**
 * Run the entry_guard_failed() function on every circuit that is
 * pending on <b>chan</b>.
 */
void
entry_guard_chan_failed(channel_t *chan)
{
  if (!chan)
    return;

  smartlist_t *pending = smartlist_new();
  circuit_get_all_pending_on_channel(pending, chan);
  SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
    if (!CIRCUIT_IS_ORIGIN(circ))
      continue;

    origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
    if (origin_circ->guard_state) {
      /* We might have no guard state if we didn't use a guard on this
       * circuit (eg it's for a fallback directory). */
      entry_guard_failed(&origin_circ->guard_state);
    }
  } SMARTLIST_FOREACH_END(circ);
  smartlist_free(pending);
}

/**
 * Return true iff every primary guard in <b>gs</b> is believed to
 * be unreachable.
 */
STATIC int
entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
{
  tor_assert(gs);
  if (!gs->primary_guards_up_to_date)
    entry_guards_update_primary(gs);
  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
    entry_guard_consider_retry(guard);
    if (guard->is_reachable != GUARD_REACHABLE_NO)
      return 0;
  } SMARTLIST_FOREACH_END(guard);
  return 1;
}

/** Wrapper for entry_guard_has_higher_priority that compares the
 * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
 * priority than <b>b</b>.
 *
 * If a restriction is provided in <b>rst</b>, then do not consider
 * <b>a</b> to have higher priority if it violates the restriction.
 */
static int
circ_state_has_higher_priority(origin_circuit_t *a,
                               const entry_guard_restriction_t *rst,
                               origin_circuit_t *b)
{
  circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
  circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);

  tor_assert(state_a);
  tor_assert(state_b);

  entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
  entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);

  if (! guard_a) {
    /* Unknown guard -- never higher priority. */
    return 0;
  } else if (! guard_b) {
    /* Known guard -- higher priority than any unknown guard. */
    return 1;
  } else  if (! entry_guard_obeys_restriction(guard_a, rst)) {
    /* Restriction violated; guard_a cannot have higher priority. */
    return 0;
  } else {
    /* Both known -- compare.*/
    return entry_guard_has_higher_priority(guard_a, guard_b);
  }
}

/**
 * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
 * and see if any of them that were previously not ready to use for
 * guard-related reasons are now ready to use. Place those circuits
 * in <b>newly_complete_out</b>, and mark them COMPLETE.
 *
 * Return 1 if we upgraded any circuits, and 0 otherwise.
 */
int
entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
                                      const smartlist_t *all_circuits_in,
                                      smartlist_t *newly_complete_out)
{
  tor_assert(gs);
  tor_assert(all_circuits_in);
  tor_assert(newly_complete_out);

  if (! entry_guards_all_primary_guards_are_down(gs)) {
    /* We only upgrade a waiting circuit if the primary guards are all
     * down. */
    log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
              "but not all primary guards were definitely down.");
    return 0;
  }

  int n_waiting = 0;
  int n_complete = 0;
  int n_complete_blocking = 0;
  origin_circuit_t *best_waiting_circuit = NULL;
  smartlist_t *all_circuits = smartlist_new();
  SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
    // We filter out circuits that aren't ours, or which we can't
    // reason about.
    circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    if (state == NULL)
      continue;
    entry_guard_t *guard = entry_guard_handle_get(state->guard);
    if (!guard || guard->in_selection != gs)
      continue;
    if (TO_CIRCUIT(circ)->marked_for_close) {
      /* Don't consider any marked for close circuits. */
      continue;
    }

    smartlist_add(all_circuits, circ);
  } SMARTLIST_FOREACH_END(circ);

  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    if (BUG(state == NULL))
      continue;

    if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
      ++n_waiting;
      if (! best_waiting_circuit ||
          circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
        best_waiting_circuit = circ;
      }
    }
  } SMARTLIST_FOREACH_END(circ);

  if (! best_waiting_circuit) {
    log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
              "but didn't find any.");
    goto no_change;
  }

  /* We'll need to keep track of what restrictions were used when picking this
   * circuit, so that we don't allow any circuit without those restrictions to
   * block it. */
  const entry_guard_restriction_t *rst_on_best_waiting =
    origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;

  /* First look at the complete circuits: Do any block this circuit? */
  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    /* "C2 "blocks" C1 if:
        * C2 obeys all the restrictions that C1 had to obey, AND
        * C2 has higher priority than C1, AND
        * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
          or C2 has been <usable_if_no_better_guard> for no more than
          {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
    */
    circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    if BUG((state == NULL))
      continue;
    if (state->state != GUARD_CIRC_STATE_COMPLETE)
      continue;
    ++n_complete;
    if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
                                       best_waiting_circuit))
      ++n_complete_blocking;
  } SMARTLIST_FOREACH_END(circ);

  if (n_complete_blocking) {
    log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
              "%d complete and %d guard-stalled. At least one complete "
              "circuit had higher priority, so not upgrading.",
              n_complete, n_waiting);
    goto no_change;
  }

  /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
          * All primary guards have reachable status of <no>.
          * There is no circuit C2 that "blocks" C1.
         Then, upgrade C1 to <complete>.""
  */
  int n_blockers_found = 0;
  const time_t state_set_at_cutoff =
    approx_time() - get_nonprimary_guard_connect_timeout();
  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    if (BUG(state == NULL))
      continue;
    if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
      continue;
    if (state->state_set_at <= state_set_at_cutoff)
      continue;
    if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
                                       best_waiting_circuit))
      ++n_blockers_found;
  } SMARTLIST_FOREACH_END(circ);

  if (n_blockers_found) {
    log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
              "%d guard-stalled, but %d pending circuit(s) had higher "
              "guard priority, so not upgrading.",
              n_waiting, n_blockers_found);
    goto no_change;
  }

  /* Okay. We have a best waiting circuit, and we aren't waiting for
     anything better.  Add all circuits with that priority to the
     list, and call them COMPLETE. */
  int n_succeeded = 0;
  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    if (BUG(state == NULL))
      continue;
    if (circ != best_waiting_circuit && rst_on_best_waiting) {
      /* Can't upgrade other circ with same priority as best; might
         be blocked. */
      continue;
    }
    if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
      continue;
    if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
      continue;

    state->state = GUARD_CIRC_STATE_COMPLETE;
    state->state_set_at = approx_time();
    smartlist_add(newly_complete_out, circ);
    ++n_succeeded;
  } SMARTLIST_FOREACH_END(circ);

  log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
           "%d guard-stalled, %d complete. %d of the guard-stalled "
           "circuit(s) had high enough priority to upgrade.",
           n_waiting, n_complete, n_succeeded);

  tor_assert_nonfatal(n_succeeded >= 1);
  smartlist_free(all_circuits);
  return 1;

 no_change:
  smartlist_free(all_circuits);
  return 0;
}

/**
 * Return true iff the circuit whose state is <b>guard_state</b> should
 * expire.
 */
int
entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
{
  if (guard_state == NULL)
    return 0;
  const time_t expire_if_waiting_since =
    approx_time() - get_nonprimary_guard_idle_timeout();
  return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
          && guard_state->state_set_at < expire_if_waiting_since);
}

/**
 * Update all derived pieces of the guard selection state in <b>gs</b>.
 * Return true iff we should stop using all previously generated circuits.
 */
int
entry_guards_update_all(guard_selection_t *gs)
{
  sampled_guards_update_from_consensus(gs);
  entry_guards_update_filtered_sets(gs);
  entry_guards_update_confirmed(gs);
  entry_guards_update_primary(gs);
  return 0;
}

/**
 * Return a newly allocated string for encoding the persistent parts of
 * <b>guard</b> to the state file. <b>dense_sampled_idx</b> refers to the
 * sampled_idx made dense for this <b>guard</b>. Encoding all guards should
 * lead to a dense array of sampled_idx in the state file.
 */
STATIC char *
entry_guard_encode_for_state(entry_guard_t *guard, int dense_sampled_idx)
{
  /*
   * The meta-format we use is K=V K=V K=V... where K can be any
   * characters excepts space and =, and V can be any characters except
   * space.  The order of entries is not allowed to matter.
   * Unrecognized K=V entries are persisted; recognized but erroneous
   * entries are corrected.
   */

  smartlist_t *result = smartlist_new();
  char tbuf[ISO_TIME_LEN+1];

  tor_assert(guard);

  smartlist_add_asprintf(result, "in=%s", guard->selection_name);
  smartlist_add_asprintf(result, "rsa_id=%s",
                         hex_str(guard->identity, DIGEST_LEN));
  if (guard->bridge_addr) {
    smartlist_add_asprintf(result, "bridge_addr=%s:%d",
                           fmt_and_decorate_addr(&guard->bridge_addr->addr),
                           guard->bridge_addr->port);
  }
  if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
    smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
  }

  format_iso_time_nospace(tbuf, guard->sampled_on_date);
  smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
  // Replacing the sampled_idx by dense array
  smartlist_add_asprintf(result, "sampled_idx=%d", dense_sampled_idx);
  if (guard->sampled_by_version) {
    smartlist_add_asprintf(result, "sampled_by=%s",
                           guard->sampled_by_version);
  }

  if (guard->unlisted_since_date > 0) {
    format_iso_time_nospace(tbuf, guard->unlisted_since_date);
    smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
  }

  smartlist_add_asprintf(result, "listed=%d",
                         (int)guard->currently_listed);

  if (guard->confirmed_idx >= 0) {
    format_iso_time_nospace(tbuf, guard->confirmed_on_date);
    smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);

    smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
  }

  const double EPSILON = 1.0e-6;

  /* Make a copy of the pathbias object, since we will want to update
     some of them */
  guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
  pb->use_successes = pathbias_get_use_success_count(guard);
  pb->successful_circuits_closed = pathbias_get_close_success_count(guard);

  #define PB_FIELD(field) do {                                          \
      if (pb->field >= EPSILON) {                                       \
        smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field);  \
      }                                                                 \
    } while (0)
  PB_FIELD(use_attempts);
  PB_FIELD(use_successes);
  PB_FIELD(circ_attempts);
  PB_FIELD(circ_successes);
  PB_FIELD(successful_circuits_closed);
  PB_FIELD(collapsed_circuits);
  PB_FIELD(unusable_circuits);
  PB_FIELD(timeouts);
  tor_free(pb);
#undef PB_FIELD

  if (guard->extra_state_fields)
    smartlist_add_strdup(result, guard->extra_state_fields);

  char *joined = smartlist_join_strings(result, " ", 0, NULL);
  SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
  smartlist_free(result);

  return joined;
}

/**
 * Extract key=val from the state string <b>s</b> and duplicate the value to
 * some string target declared in entry_guard_parse_from_state
 */
static void
parse_from_state_set_vals(const char *s, smartlist_t *entries, smartlist_t
    *extra, strmap_t *vals)
{
    smartlist_split_string(entries, s, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);

    SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
      const char *eq = strchr(entry, '=');
      if (!eq) {
        smartlist_add(extra, entry);
        continue;
      }
      char *key = tor_strndup(entry, eq-entry);
      char **target = strmap_get(vals, key);
      if (target == NULL || *target != NULL) {
        /* unrecognized or already set */
        smartlist_add(extra, entry);
        tor_free(key);
        continue;
      }

      *target = tor_strdup(eq+1);
      tor_free(key);
      tor_free(entry);
    } SMARTLIST_FOREACH_END(entry);
}

/**
 * Handle part of the parsing state file logic, focused on time related things
 */
static void
parse_from_state_handle_time(entry_guard_t *guard, char *sampled_on, char
    *unlisted_since, char *confirmed_on)
{
#define HANDLE_TIME(field) do {                                 \
    if (field) {                                                \
      int r = parse_iso_time_nospace(field, &field ## _time);   \
      if (r < 0) {                                              \
        log_warn(LD_CIRC, "Unable to parse %s %s from guard",   \
                 #field, escaped(field));                       \
        field##_time = -1;                                      \
      }                                                         \
    }                                                           \
  } while (0)

  time_t sampled_on_time = 0;
  time_t unlisted_since_time = 0;
  time_t confirmed_on_time = 0;

  HANDLE_TIME(sampled_on);
  HANDLE_TIME(unlisted_since);
  HANDLE_TIME(confirmed_on);

  if (sampled_on_time <= 0)
    sampled_on_time = approx_time();
  if (unlisted_since_time < 0)
    unlisted_since_time = 0;
  if (confirmed_on_time < 0)
    confirmed_on_time = 0;

  #undef HANDLE_TIME

  guard->sampled_on_date = sampled_on_time;
  guard->unlisted_since_date = unlisted_since_time;
  guard->confirmed_on_date = confirmed_on_time;
}

/**
 * Given a string generated by entry_guard_encode_for_state(), parse it
 * (if possible) and return an entry_guard_t object for it.  Return NULL
 * on complete failure.
 */
STATIC entry_guard_t *
entry_guard_parse_from_state(const char *s)
{
  /* Unrecognized entries get put in here. */
  smartlist_t *extra = smartlist_new();

  /* These fields get parsed from the string. */
  char *in = NULL;
  char *rsa_id = NULL;
  char *nickname = NULL;
  char *sampled_on = NULL;
  char *sampled_idx = NULL;
  char *sampled_by = NULL;
  char *unlisted_since = NULL;
  char *listed  = NULL;
  char *confirmed_on = NULL;
  char *confirmed_idx = NULL;
  char *bridge_addr = NULL;

  // pathbias
  char *pb_use_attempts = NULL;
  char *pb_use_successes = NULL;
  char *pb_circ_attempts = NULL;
  char *pb_circ_successes = NULL;
  char *pb_successful_circuits_closed = NULL;
  char *pb_collapsed_circuits = NULL;
  char *pb_unusable_circuits = NULL;
  char *pb_timeouts = NULL;
  int invalid_sampled_idx = get_max_sample_size_absolute();

  /* Split up the entries.  Put the ones we know about in strings and the
   * rest in "extra". */
  {
    smartlist_t *entries = smartlist_new();

    strmap_t *vals = strmap_new(); // Maps keyword to location
#define FIELD(f) \
    strmap_set(vals, #f, &f);
    FIELD(in);
    FIELD(rsa_id);
    FIELD(nickname);
    FIELD(sampled_on);
    FIELD(sampled_idx);
    FIELD(sampled_by);
    FIELD(unlisted_since);
    FIELD(listed);
    FIELD(confirmed_on);
    FIELD(confirmed_idx);
    FIELD(bridge_addr);
    FIELD(pb_use_attempts);
    FIELD(pb_use_successes);
    FIELD(pb_circ_attempts);
    FIELD(pb_circ_successes);
    FIELD(pb_successful_circuits_closed);
    FIELD(pb_collapsed_circuits);
    FIELD(pb_unusable_circuits);
    FIELD(pb_timeouts);
#undef FIELD
    /* Extract from s the key=val that we recognize, put the others in extra*/
    parse_from_state_set_vals(s, entries, extra, vals);

    smartlist_free(entries);
    strmap_free(vals, NULL);
  }

  entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
  guard->is_persistent = 1;

  if (in == NULL) {
    log_warn(LD_CIRC, "Guard missing 'in' field");
    goto err;
  }

  guard->selection_name = in;
  in = NULL;

  if (rsa_id == NULL) {
    log_warn(LD_CIRC, "Guard missing RSA ID field");
    goto err;
  }

  /* Process the identity and nickname. */
  if (base16_decode(guard->identity, sizeof(guard->identity),
                    rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
    log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
    goto err;
  }

  if (nickname) {
    strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
  } else {
    guard->nickname[0]='$';
    base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
                  guard->identity, DIGEST_LEN);
  }

  if (bridge_addr) {
    tor_addr_port_t res;
    memset(&res, 0, sizeof(res));
    int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
                                &res.addr, &res.port, -1);
    if (r == 0)
      guard->bridge_addr = tor_memdup(&res, sizeof(res));
    /* On error, we already warned. */
  }

  /* Process the various time fields. */
  parse_from_state_handle_time(guard, sampled_on, unlisted_since,
      confirmed_on);

  /* Take sampled_by_version verbatim. */
  guard->sampled_by_version = sampled_by;
  sampled_by = NULL; /* prevent free */
  /* Listed is a boolean */
  if (listed && strcmp(listed, "0"))
    guard->currently_listed = 1;

  /* The index is a nonnegative integer. */
  guard->confirmed_idx = -1;
  if (confirmed_idx) {
    int ok=1;
    long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
    if (! ok) {
      log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
               escaped(confirmed_idx));
    } else {
      guard->confirmed_idx = (int)idx;
    }
  }

  if (sampled_idx) {
    int ok = 1;
    long idx = tor_parse_long(sampled_idx, 10, 0, INT_MAX, &ok, NULL);
    if (!ok) {
      log_warn(LD_GUARD, "Guard has invalid sampled_idx %s",
          escaped(sampled_idx));
      /* set it to a idx higher than the max sample size */
      guard->sampled_idx = invalid_sampled_idx++;
    } else {
      guard->sampled_idx = (int)idx;
    }
  } else if (confirmed_idx) {
    /* This state has been written by an older Tor version which did not have
     * sample ordering  */

    guard->sampled_idx = guard->confirmed_idx;
  } else {
    log_info(LD_GUARD, "The state file seems to be into a status that could"
             " yield to weird entry node selection: we're missing both a"
             " sampled_idx and a confirmed_idx.");
    guard->sampled_idx = invalid_sampled_idx++;
  }

  /* Anything we didn't recognize gets crammed together */
  if (smartlist_len(extra) > 0) {
    guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
  }

  /* initialize non-persistent fields */
  guard->is_reachable = GUARD_REACHABLE_MAYBE;

#define PB_FIELD(field)                                                 \
  do {                                                                  \
    if (pb_ ## field) {                                                 \
      int ok = 1;                                                       \
      double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL);   \
      if (! ok) {                                                       \
        log_warn(LD_CIRC, "Guard has invalid pb_%s %s",                 \
                 #field, pb_ ## field);                                 \
      } else {                                                          \
        guard->pb.field = r;                                            \
      }                                                                 \
    }                                                                   \
  } while (0)
  PB_FIELD(use_attempts);
  PB_FIELD(use_successes);
  PB_FIELD(circ_attempts);
  PB_FIELD(circ_successes);
  PB_FIELD(successful_circuits_closed);
  PB_FIELD(collapsed_circuits);
  PB_FIELD(unusable_circuits);
  PB_FIELD(timeouts);
#undef PB_FIELD

  pathbias_check_use_success_count(guard);
  pathbias_check_close_success_count(guard);

  /* We update everything on this guard later, after we've parsed
   * everything.  */

  goto done;

 err:
  // only consider it an error if the guard state was totally unparseable.
  entry_guard_free(guard);
  guard = NULL;

 done:
  tor_free(in);
  tor_free(rsa_id);
  tor_free(nickname);
  tor_free(sampled_on);
  tor_free(sampled_by);
  tor_free(unlisted_since);
  tor_free(listed);
  tor_free(confirmed_on);
  tor_free(confirmed_idx);
  tor_free(sampled_idx);
  tor_free(bridge_addr);
  tor_free(pb_use_attempts);
  tor_free(pb_use_successes);
  tor_free(pb_circ_attempts);
  tor_free(pb_circ_successes);
  tor_free(pb_successful_circuits_closed);
  tor_free(pb_collapsed_circuits);
  tor_free(pb_unusable_circuits);
  tor_free(pb_timeouts);

  SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
  smartlist_free(extra);

  return guard;
}

/**
 * Replace the Guards entries in <b>state</b> with a list of all our sampled
 * guards.
 */
static void
entry_guards_update_guards_in_state(or_state_t *state)
{
  if (!guard_contexts)
    return;
  config_line_t *lines = NULL;
  config_line_t **nextline = &lines;

  SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
    int i = 0;
    SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
      if (guard->is_persistent == 0)
        continue;
      *nextline = tor_malloc_zero(sizeof(config_line_t));
      (*nextline)->key = tor_strdup("Guard");
      (*nextline)->value = entry_guard_encode_for_state(guard, i);
      nextline = &(*nextline)->next;
      i++;
    } SMARTLIST_FOREACH_END(guard);
  } SMARTLIST_FOREACH_END(gs);

  config_free_lines(state->Guard);
  state->Guard = lines;
}

/**
 * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
 * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
 * check whether replacing would work.)
 */
static int
entry_guards_load_guards_from_state(or_state_t *state, int set)
{
  const config_line_t *line = state->Guard;
  int n_errors = 0;

  if (!guard_contexts)
    guard_contexts = smartlist_new();

  /* Wipe all our existing guard info. (we shouldn't have any, but
   * let's be safe.) */
  if (set) {
    SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
      guard_selection_free(gs);
      if (curr_guard_context == gs)
        curr_guard_context = NULL;
      SMARTLIST_DEL_CURRENT(guard_contexts, gs);
    } SMARTLIST_FOREACH_END(gs);
  }

  for ( ; line != NULL; line = line->next) {
    entry_guard_t *guard = entry_guard_parse_from_state(line->value);
    if (guard == NULL) {
      ++n_errors;
      continue;
    }
    tor_assert(guard->selection_name);
    if (!strcmp(guard->selection_name, "legacy")) {
      ++n_errors;
      entry_guard_free(guard);
      continue;
    }

    if (set) {
      guard_selection_t *gs;
      gs = get_guard_selection_by_name(guard->selection_name,
                                       GS_TYPE_INFER, 1);
      tor_assert(gs);
      smartlist_add(gs->sampled_entry_guards, guard);
      guard->in_selection = gs;
      /* Recompute the next_sampled_id from the state. We do not assume that
       * sampled guards appear in the correct order within the file, and we
       * need to know what would be the next sampled idx to give to any
       * new sampled guard (i.e., max of guard->sampled_idx + 1)*/
      if (gs->next_sampled_idx <= guard->sampled_idx) {
        gs->next_sampled_idx = guard->sampled_idx + 1;
      }

    } else {
      entry_guard_free(guard);
    }
  }

  if (set) {
    SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
      /** Guards should be in sample order within the file, but it is maybe
       * better NOT to assume that. Let's order them before updating lists
       */
      smartlist_sort(gs->sampled_entry_guards, compare_guards_by_sampled_idx);
      entry_guards_update_all(gs);
    } SMARTLIST_FOREACH_END(gs);
  }
  return n_errors ? -1 : 0;
}

/** If <b>digest</b> matches the identity of any node in the
 * entry_guards list for the provided guard selection state,
 return that node. Else return NULL. */
entry_guard_t *
entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
                                                 const char *digest)
{
  return get_sampled_guard_with_id(gs, (const uint8_t*)digest);
}

/** Return the node_t associated with a single entry_guard_t. May
 * return NULL if the guard is not currently in the consensus. */
const node_t *
entry_guard_find_node(const entry_guard_t *guard)
{
  tor_assert(guard);
  return node_get_by_id(guard->identity);
}

/** If <b>digest</b> matches the identity of any node in the
 * entry_guards list for the default guard selection state,
 return that node. Else return NULL. */
entry_guard_t *
entry_guard_get_by_id_digest(const char *digest)
{
  return entry_guard_get_by_id_digest_for_guard_selection(
      get_guard_selection_info(), digest);
}

/** We are about to connect to bridge with identity <b>digest</b> to fetch its
 *  descriptor. Create a new guard state for this connection and return it. */
circuit_guard_state_t *
get_guard_state_for_bridge_desc_fetch(const char *digest)
{
  circuit_guard_state_t *guard_state = NULL;
  entry_guard_t *guard = NULL;

  guard = entry_guard_get_by_id_digest_for_guard_selection(
                                    get_guard_selection_info(), digest);
  if (!guard) {
    return NULL;
  }

  /* Update the guard last_tried_to_connect time since it's checked by the
   * guard subsystem. */
  guard->last_tried_to_connect = approx_time();

  /* Create the guard state */
  guard_state = circuit_guard_state_new(guard,
                                        GUARD_CIRC_STATE_USABLE_ON_COMPLETION,
                                        NULL);

  return guard_state;
}

/** Release all storage held by <b>e</b>. */
STATIC void
entry_guard_free_(entry_guard_t *e)
{
  if (!e)
    return;
  entry_guard_handles_clear(e);
  tor_free(e->sampled_by_version);
  tor_free(e->extra_state_fields);
  tor_free(e->selection_name);
  tor_free(e->bridge_addr);
  tor_free(e);
}

/** Return 0 if we're fine adding arbitrary routers out of the
 * directory to our entry guard list, or return 1 if we have a
 * list already and we must stick to it.
 */
int
entry_list_is_constrained(const or_options_t *options)
{
  // XXXX #21425 look at the current selection.
  if (options->EntryNodes)
    return 1;
  if (options->UseBridges)
    return 1;
  return 0;
}

/** Return the number of bridges that have descriptors that are marked with
 * purpose 'bridge' and are running. If use_maybe_reachable is
 * true, include bridges that might be reachable in the count.
 * Otherwise, if it is false, only include bridges that have recently been
 * found running in the count.
 *
 * We use this function to decide if we're ready to start building
 * circuits through our bridges, or if we need to wait until the
 * directory "server/authority" requests finish. */
MOCK_IMPL(int,
num_bridges_usable,(int use_maybe_reachable))
{
  int n_options = 0;

  if (BUG(!get_options()->UseBridges)) {
    return 0;
  }
  guard_selection_t *gs  = get_guard_selection_info();
  if (BUG(gs->type != GS_TYPE_BRIDGE)) {
    return 0;
  }

  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    /* Not a bridge, or not one we are configured to be able to use. */
    if (! guard->is_filtered_guard)
      continue;
    /* Definitely not usable */
    if (guard->is_reachable == GUARD_REACHABLE_NO)
      continue;
    /* If we want to be really sure the bridges will work, skip maybes */
    if (!use_maybe_reachable && guard->is_reachable == GUARD_REACHABLE_MAYBE)
      continue;
    if (tor_digest_is_zero(guard->identity))
      continue;
    const node_t *node = node_get_by_id(guard->identity);
    if (node && node->ri)
      ++n_options;
  } SMARTLIST_FOREACH_END(guard);

  return n_options;
}

/** Check the pathbias use success count of <b>node</b> and disable it if it
 *  goes over our thresholds. */
static void
pathbias_check_use_success_count(entry_guard_t *node)
{
  const or_options_t *options = get_options();
  const double EPSILON = 1.0e-9;

  /* Note: We rely on the < comparison here to allow us to set a 0
   * rate and disable the feature entirely. If refactoring, don't
   * change to <= */
  if (node->pb.use_attempts > EPSILON &&
      pathbias_get_use_success_count(node)/node->pb.use_attempts
      < pathbias_get_extreme_use_rate(options) &&
      pathbias_get_dropguards(options)) {
    node->pb.path_bias_disabled = 1;
    log_info(LD_GENERAL,
             "Path use bias is too high (%f/%f); disabling node %s",
             node->pb.circ_successes, node->pb.circ_attempts,
             node->nickname);
  }
}

/** Check the pathbias close count of <b>node</b> and disable it if it goes
 *  over our thresholds. */
static void
pathbias_check_close_success_count(entry_guard_t *node)
{
  const or_options_t *options = get_options();
  const double EPSILON = 1.0e-9;

  /* Note: We rely on the < comparison here to allow us to set a 0
   * rate and disable the feature entirely. If refactoring, don't
   * change to <= */
  if (node->pb.circ_attempts > EPSILON &&
      pathbias_get_close_success_count(node)/node->pb.circ_attempts
      < pathbias_get_extreme_rate(options) &&
      pathbias_get_dropguards(options)) {
    node->pb.path_bias_disabled = 1;
    log_info(LD_GENERAL,
             "Path bias is too high (%f/%f); disabling node %s",
             node->pb.circ_successes, node->pb.circ_attempts,
             node->nickname);
  }
}

/** Parse <b>state</b> and learn about the entry guards it describes.
 * If <b>set</b> is true, and there are no errors, replace the guard
 * list in the default guard selection context with what we find.
 * On success, return 0. On failure, alloc into *<b>msg</b> a string
 * describing the error, and return -1.
 */
int
entry_guards_parse_state(or_state_t *state, int set, char **msg)
{
  entry_guards_dirty = 0;
  int r1 = entry_guards_load_guards_from_state(state, set);
  entry_guards_dirty = 0;

  if (r1 < 0) {
    if (msg && *msg == NULL) {
      *msg = tor_strdup("parsing error");
    }
    return -1;
  }
  return 0;
}

/** How long will we let a change in our guard nodes stay un-saved
 * when we are trying to avoid disk writes? */
#define SLOW_GUARD_STATE_FLUSH_TIME 600
/** How long will we let a change in our guard nodes stay un-saved
 * when we are not trying to avoid disk writes? */
#define FAST_GUARD_STATE_FLUSH_TIME 30

/** Our list of entry guards has changed for a particular guard selection
 * context, or some element of one of our entry guards has changed for one.
 * Write the changes to disk within the next few minutes.
 */
void
entry_guards_changed_for_guard_selection(guard_selection_t *gs)
{
  time_t when;

  tor_assert(gs != NULL);

  entry_guards_dirty = 1;

  if (get_options()->AvoidDiskWrites)
    when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  else
    when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;

  /* or_state_save() will call entry_guards_update_state() and
     entry_guards_update_guards_in_state()
  */
  or_state_mark_dirty(get_or_state(), when);

  /* Schedule a re-assessment of whether we have enough dir info to
   * use the network. When we add or remove or disable or enable a
   * guard, the decision could shift. */
  router_dir_info_changed();
}

/** Our list of entry guards has changed for the default guard selection
 * context, or some element of one of our entry guards has changed. Write
 * the changes to disk within the next few minutes.
 */
void
entry_guards_changed(void)
{
  entry_guards_changed_for_guard_selection(get_guard_selection_info());
}

/** If the entry guard info has not changed, do nothing and return.
 * Otherwise, free the EntryGuards piece of <b>state</b> and create
 * a new one out of the global entry_guards list, and then mark
 * <b>state</b> dirty so it will get saved to disk.
 */
void
entry_guards_update_state(or_state_t *state)
{
  entry_guards_dirty = 0;

  // Handles all guard info.
  entry_guards_update_guards_in_state(state);

  entry_guards_dirty = 0;

  if (!get_options()->AvoidDiskWrites)
    or_state_mark_dirty(get_or_state(), 0);
  entry_guards_dirty = 0;
}

/** Return true iff the circuit's guard can succeed, that is, can be used. */
int
entry_guard_could_succeed(const circuit_guard_state_t *guard_state)
{
  if (get_options()->UseEntryGuards == 0) {
    /* we're fine with this circuit's first hop, because we're not
     * configured to use entry guards. */
    return 1;
  }

  if (!guard_state) {
    return 0;
  }

  entry_guard_t *guard = entry_guard_handle_get(guard_state->guard);
  if (!guard || BUG(guard->in_selection == NULL)) {
    return 0;
  }

  return 1;
}

/**
 * Format a single entry guard in the format expected by the controller.
 * Return a newly allocated string.
 */
STATIC char *
getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
{
  const char *status = NULL;
  time_t when = 0;
  const node_t *node;
  char tbuf[ISO_TIME_LEN+1];
  char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];

  /* This is going to be a bit tricky, since the status
   * codes weren't really intended for prop271 guards.
   *
   * XXXX use a more appropriate format for exporting this information
   */
  if (e->confirmed_idx < 0) {
    status = "never-connected";
  } else if (! e->currently_listed) {
    when = e->unlisted_since_date;
    status = "unusable";
  } else if (! e->is_filtered_guard) {
    status = "unusable";
  } else if (e->is_reachable == GUARD_REACHABLE_NO) {
    when = e->failing_since;
    status = "down";
  } else {
    status = "up";
  }

  node = entry_guard_find_node(e);
  if (node) {
    node_get_verbose_nickname(node, nbuf);
  } else {
    nbuf[0] = '$';
    base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
    /* e->nickname field is not very reliable if we don't know about
     * this router any longer; don't include it. */
  }

  char *result = NULL;
  if (when) {
    format_iso_time(tbuf, when);
    tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
  } else {
    tor_asprintf(&result, "%s %s\n", nbuf, status);
  }
  return result;
}

/** If <b>question</b> is the string "entry-guards", then dump
 * to *<b>answer</b> a newly allocated string describing all of
 * the nodes in the global entry_guards list. See control-spec.txt
 * for details.
 * For backward compatibility, we also handle the string "helper-nodes".
 *
 * XXX this should be totally redesigned after prop 271 too, and that's
 * going to take some control spec work.
 * */
int
getinfo_helper_entry_guards(control_connection_t *conn,
                            const char *question, char **answer,
                            const char **errmsg)
{
  guard_selection_t *gs = get_guard_selection_info();

  tor_assert(gs != NULL);

  (void) conn;
  (void) errmsg;

  if (!strcmp(question,"entry-guards") ||
      !strcmp(question,"helper-nodes")) {
    const smartlist_t *guards;
    guards = gs->sampled_entry_guards;

    smartlist_t *sl = smartlist_new();

    SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
      char *cp = getinfo_helper_format_single_entry_guard(e);
      smartlist_add(sl, cp);
    } SMARTLIST_FOREACH_END(e);
    *answer = smartlist_join_strings(sl, "", 0, NULL);
    SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
    smartlist_free(sl);
  }
  return 0;
}

/* Given the original bandwidth of a guard and its guardfraction,
 * calculate how much bandwidth the guard should have as a guard and
 * as a non-guard.
 *
 * Quoting from proposal236:
 *
 *   Let Wpf denote the weight from the 'bandwidth-weights' line a
 *   client would apply to N for position p if it had the guard
 *   flag, Wpn the weight if it did not have the guard flag, and B the
 *   measured bandwidth of N in the consensus.  Then instead of choosing
 *   N for position p proportionally to Wpf*B or Wpn*B, clients should
 *   choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
 *
 * This function fills the <b>guardfraction_bw</b> structure. It sets
 * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
 */
void
guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
                                  int orig_bandwidth,
                                  uint32_t guardfraction_percentage)
{
  double guardfraction_fraction;

  /* Turn the percentage into a fraction. */
  tor_assert(guardfraction_percentage <= 100);
  guardfraction_fraction = guardfraction_percentage / 100.0;

  long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  tor_assert(guard_bw <= INT_MAX);

  guardfraction_bw->guard_bw = (int) guard_bw;

  guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
}

/** Helper: Update the status of all entry guards, in whatever algorithm
 * is used. Return true if we should stop using all previously generated
 * circuits, by calling circuit_mark_all_unused_circs() and
 * circuit_mark_all_dirty_circs_as_unusable().
 */
int
guards_update_all(void)
{
  int mark_circuits = 0;
  if (update_guard_selection_choice(get_options()))
    mark_circuits = 1;

  tor_assert(curr_guard_context);

  if (entry_guards_update_all(curr_guard_context))
    mark_circuits = 1;

  return mark_circuits;
}

/** Helper: pick a guard for a circuit, with whatever algorithm is
    used. */
const node_t *
guards_choose_guard(cpath_build_state_t *state,
                    uint8_t purpose,
                    circuit_guard_state_t **guard_state_out)
{
  const node_t *r = NULL;
  const uint8_t *exit_id = NULL;
  entry_guard_restriction_t *rst = NULL;

  /* Only apply restrictions if we have a specific exit node in mind, and only
   * if we are not doing vanguard circuits: we don't want to apply guard
   * restrictions to vanguard circuits. */
  if (state && !circuit_should_use_vanguards(purpose) &&
      (exit_id = build_state_get_exit_rsa_id(state))) {
    /* We're building to a targeted exit node, so that node can't be
     * chosen as our guard for this circuit.  Remember that fact in a
     * restriction. */
    rst = guard_create_exit_restriction(exit_id);
    tor_assert(rst);
  }
  if (entry_guard_pick_for_circuit(get_guard_selection_info(),
                                   GUARD_USAGE_TRAFFIC,
                                   rst,
                                   &r,
                                   guard_state_out) < 0) {
    tor_assert(r == NULL);
  }
  return r;
}

/** Remove all currently listed entry guards for a given guard selection
 * context.  This frees and replaces <b>gs</b>, so don't use <b>gs</b>
 * after calling this function. */
void
remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
{
  // This function shouldn't exist. XXXX
  tor_assert(gs != NULL);
  char *old_name = tor_strdup(gs->name);
  guard_selection_type_t old_type = gs->type;

  SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
    control_event_guard(entry->nickname, entry->identity, "DROPPED");
  });

  if (gs == curr_guard_context) {
    curr_guard_context = NULL;
  }

  smartlist_remove(guard_contexts, gs);
  guard_selection_free(gs);

  gs = get_guard_selection_by_name(old_name, old_type, 1);
  entry_guards_changed_for_guard_selection(gs);
  tor_free(old_name);
}

/** Remove all currently listed entry guards, so new ones will be chosen.
 *
 * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
 * command, which is deprecated.
 */
void
remove_all_entry_guards(void)
{
  remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
}

/** Helper: pick a directory guard, with whatever algorithm is used. */
const node_t *
guards_choose_dirguard(uint8_t dir_purpose,
                       circuit_guard_state_t **guard_state_out)
{
  const node_t *r = NULL;
  entry_guard_restriction_t *rst = NULL;

  /* If we are fetching microdescs, don't query outdated dirservers. */
  if (dir_purpose == DIR_PURPOSE_FETCH_MICRODESC) {
    rst = guard_create_dirserver_md_restriction();
  }

  if (entry_guard_pick_for_circuit(get_guard_selection_info(),
                                   GUARD_USAGE_DIRGUARD,
                                   rst,
                                   &r,
                                   guard_state_out) < 0) {
    tor_assert(r == NULL);
  }
  return r;
}

/**
 * If we're running with a constrained guard set, then maybe mark our guards
 * usable.  Return 1 if we do; 0 if we don't.
 */
int
guards_retry_optimistic(const or_options_t *options)
{
  if (! entry_list_is_constrained(options))
    return 0;

  mark_primary_guards_maybe_reachable(get_guard_selection_info());

  return 1;
}

/**
 * Check if we are missing any crucial dirinfo for the guard subsystem to
 * work. Return NULL if everything went well, otherwise return a newly
 * allocated string with an informative error message. In the latter case, use
 * the general descriptor information <b>using_mds</b>, <b>num_present</b> and
 * <b>num_usable</b> to improve the error message. */
char *
guard_selection_get_err_str_if_dir_info_missing(guard_selection_t *gs,
                                        int using_mds,
                                        int num_present, int num_usable)
{
  if (!gs->primary_guards_up_to_date)
    entry_guards_update_primary(gs);

  char *ret_str = NULL;
  int n_missing_descriptors = 0;
  int n_considered = 0;
  int num_primary_to_check;

  /* We want to check for the descriptor of at least the first two primary
   * guards in our list, since these are the guards that we typically use for
   * circuits. */
  num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
  num_primary_to_check++;

  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
    entry_guard_consider_retry(guard);
    if (guard->is_reachable == GUARD_REACHABLE_NO)
      continue;
    n_considered++;
    if (!guard_has_descriptor(guard))
      n_missing_descriptors++;
    if (n_considered >= num_primary_to_check)
      break;
  } SMARTLIST_FOREACH_END(guard);

  /* If we are not missing any descriptors, return NULL. */
  if (!n_missing_descriptors) {
    return NULL;
  }

  /* otherwise return a helpful error string */
  tor_asprintf(&ret_str, "We're missing descriptors for %d/%d of our "
               "primary entry guards (total %sdescriptors: %d/%d). "
               "That's ok. We will try to fetch missing descriptors soon.",
               n_missing_descriptors, num_primary_to_check,
               using_mds?"micro":"", num_present, num_usable);

  return ret_str;
}

/** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
 * the default guard selection. */
char *
entry_guards_get_err_str_if_dir_info_missing(int using_mds,
                                     int num_present, int num_usable)
{
  return guard_selection_get_err_str_if_dir_info_missing(
                                                 get_guard_selection_info(),
                                                 using_mds,
                                                 num_present, num_usable);
}

/** Free one guard selection context */
STATIC void
guard_selection_free_(guard_selection_t *gs)
{
  if (!gs) return;

  tor_free(gs->name);

  if (gs->sampled_entry_guards) {
    SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
                      entry_guard_free(e));
    smartlist_free(gs->sampled_entry_guards);
    gs->sampled_entry_guards = NULL;
  }

  smartlist_free(gs->confirmed_entry_guards);
  smartlist_free(gs->primary_entry_guards);

  tor_free(gs);
}

/**********************************************************************/

/** Layer2 guard subsystem (vanguards-lite) used for onion service circuits */

/** A simple representation of a layer2 guard. We just need its identity so
 *  that we feed it into a routerset, and a sampled timestamp to do expiration
 *  checks. */
typedef struct layer2_guard_t {
  /** Identity of the guard */
  char identity[DIGEST_LEN];
  /** When does this guard expire? (randomized timestamp) */
  time_t expire_on_date;
} layer2_guard_t;

#define layer2_guard_free(val) \
  FREE_AND_NULL(layer2_guard_t, layer2_guard_free_, (val))

/** Return true if the vanguards-lite subsystem is enabled */
bool
vanguards_lite_is_enabled(void)
{
  /* First check torrc option and then maybe also the consensus parameter. */
  const or_options_t *options = get_options();

  /* If the option is explicitly disabled, that's the final word here */
  if (options->VanguardsLiteEnabled == 0) {
    return false;
  }

  /* If the option is set to auto, then check the consensus parameter */
  if (options->VanguardsLiteEnabled == -1) {
    return networkstatus_get_param(NULL, "vanguards-lite-enabled",
                                   1, /* default to "on" */
                                   0, 1);
  }

  /* else it's enabled */
  tor_assert_nonfatal(options->VanguardsLiteEnabled == 1);
  return options->VanguardsLiteEnabled;
}

static void
layer2_guard_free_(layer2_guard_t *l2)
{
  if (!l2) {
    return;
  }

  tor_free(l2);
}

/** Global list and routerset of L2 guards. They are both synced and they get
 * updated periodically. We need both the list and the routerset: we use the
 * smartlist to keep track of expiration times and the routerset is what we
 * return to the users of this subsystem. */
static smartlist_t *layer2_guards = NULL;
static routerset_t *layer2_routerset = NULL;

/** Number of L2 guards */
#define NUMBER_SECOND_GUARDS 4
/** Make sure that the number of L2 guards is less than the number of
 *  MAX_SANE_RESTRICTED_NODES */
CTASSERT(NUMBER_SECOND_GUARDS < 20);

/** Lifetime of L2 guards:
 *  1 to 12 days, for an average of a week using the max(x,x) distribution */
#define MIN_SECOND_GUARD_LIFETIME (3600*24)
#define MAX_SECOND_GUARD_LIFETIME (3600*24*12)

/** Return the number of guards our L2 guardset should have */
static int
get_number_of_layer2_hs_guards(void)
{
  return (int) networkstatus_get_param(NULL,
                                        "guard-hs-l2-number",
                                        NUMBER_SECOND_GUARDS,
                                        1, 19);
}

/** Return the minimum lifetime of L2 guards */
static int
get_min_lifetime_of_layer2_hs_guards(void)
{
  return (int) networkstatus_get_param(NULL,
                                       "guard-hs-l2-lifetime-min",
                                       MIN_SECOND_GUARD_LIFETIME,
                                       1, INT32_MAX);
}

/** Return the maximum lifetime of L2 guards */
static int
get_max_lifetime_of_layer2_hs_guards(void)
{
  return (int) networkstatus_get_param(NULL,
                                        "guard-hs-l2-lifetime-max",
                                       MAX_SECOND_GUARD_LIFETIME,
                                       1, INT32_MAX);
}

/**
 * Sample and return a lifetime for an L2 guard.
 *
 * Lifetime randomized uniformly between min and max consensus params.
 */
static int
get_layer2_hs_guard_lifetime(void)
{
  int min = get_min_lifetime_of_layer2_hs_guards();
  int max = get_max_lifetime_of_layer2_hs_guards();

  if (BUG(min >= max)) {
    return min;
  }

  return crypto_rand_int_range(min, max);
}

/** Maintain the L2 guard list. Make sure the list contains enough guards, do
 *  expirations as necessary, and keep all the data structures of this
 *  subsystem synchronized */
void
maintain_layer2_guards(void)
{
  if (!router_have_minimum_dir_info()) {
    return;
  }

  /* Create the list if it doesn't exist */
  if (!layer2_guards) {
    layer2_guards = smartlist_new();
  }

  /* Go through the list and perform any needed expirations */
  SMARTLIST_FOREACH_BEGIN(layer2_guards, layer2_guard_t *, g) {
    /* Expire based on expiration date */
    if (g->expire_on_date <= approx_time()) {
      log_info(LD_GENERAL, "Removing expired Layer2 guard %s",
               safe_str_client(hex_str(g->identity, DIGEST_LEN)));
      // Nickname may be gone from consensus and doesn't matter anyway
      control_event_guard("None", g->identity, "BAD_L2");
      layer2_guard_free(g);
      SMARTLIST_DEL_CURRENT_KEEPORDER(layer2_guards, g);
      continue;
    }

    /* Expire if relay has left consensus */
    if (router_get_consensus_status_by_id(g->identity) == NULL) {
      log_info(LD_GENERAL, "Removing missing Layer2 guard %s",
               safe_str_client(hex_str(g->identity, DIGEST_LEN)));
      // Nickname may be gone from consensus and doesn't matter anyway
      control_event_guard("None", g->identity, "BAD_L2");
      layer2_guard_free(g);
      SMARTLIST_DEL_CURRENT_KEEPORDER(layer2_guards, g);
      continue;
    }
  } SMARTLIST_FOREACH_END(g);

  /* Find out how many guards we need to add */
  int new_guards_needed_n =
    get_number_of_layer2_hs_guards() - smartlist_len(layer2_guards);
  if (new_guards_needed_n <= 0) {
    return;
  }

  log_info(LD_GENERAL, "Adding %d guards to Layer2 routerset",
           new_guards_needed_n);

  /* Add required guards to the list */
  smartlist_t *excluded = smartlist_new();
  for (int i = 0; i < new_guards_needed_n; i++) {
    const node_t *choice = NULL;
    const or_options_t *options = get_options();
    /* Pick Stable nodes */
    router_crn_flags_t flags = CRN_NEED_DESC|CRN_NEED_UPTIME;
    choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
    if (!choice) {
      break;
    }

    /* We found our node: create an L2 guard out of it */
    layer2_guard_t *layer2_guard = tor_malloc_zero(sizeof(layer2_guard_t));
    memcpy(layer2_guard->identity, choice->identity, DIGEST_LEN);
    layer2_guard->expire_on_date = approx_time() +
      get_layer2_hs_guard_lifetime();
    smartlist_add(layer2_guards, layer2_guard);
    log_info(LD_GENERAL, "Adding Layer2 guard %s",
             safe_str_client(hex_str(layer2_guard->identity, DIGEST_LEN)));
    // Nickname can also be None here because it is looked up later
    control_event_guard("None", layer2_guard->identity,
                        "GOOD_L2");
    /* Exclude this node and its family so that we don't double-pick. */
    nodelist_add_node_and_family(excluded, choice);
  }

  /* Some cleanup */
  smartlist_free(excluded);

  /* Now that the list is up to date, synchronize the routerset */
  routerset_free(layer2_routerset);
  layer2_routerset = routerset_new();

  SMARTLIST_FOREACH_BEGIN (layer2_guards, layer2_guard_t *, g) {
    routerset_parse(layer2_routerset,
                    hex_str(g->identity, DIGEST_LEN),
                    "l2 guards");
  } SMARTLIST_FOREACH_END(g);
}

/**
 * Reset vanguards-lite list(s).
 *
 * Used for SIGNAL NEWNYM.
 */
void
purge_vanguards_lite(void)
{
  if (!layer2_guards)
    return;

  /* Go through the list and perform any needed expirations */
  SMARTLIST_FOREACH_BEGIN(layer2_guards, layer2_guard_t *, g) {
    layer2_guard_free(g);
  } SMARTLIST_FOREACH_END(g);

  smartlist_clear(layer2_guards);

  /* Pick new l2 guards */
  maintain_layer2_guards();
}

/** Return a routerset containing the L2 guards or NULL if it's not yet
 *  initialized. Callers must not free the routerset. Designed for use in
 *  pick_vanguard_middle_node() and should not be used anywhere else. Do not
 *  store this pointer -- any future calls to maintain_layer2_guards() and
 *  purge_vanguards_lite() can invalidate it. */
const routerset_t *
get_layer2_guards(void)
{
  if (!layer2_guards) {
    maintain_layer2_guards();
  }

  return layer2_routerset;
}

/*****************************************************************************/

/** Release all storage held by the list of entry guards and related
 * memory structs. */
void
entry_guards_free_all(void)
{
  /* Null out the default */
  curr_guard_context = NULL;
  /* Free all the guard contexts */
  if (guard_contexts != NULL) {
    SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
      guard_selection_free(gs);
    } SMARTLIST_FOREACH_END(gs);
    smartlist_free(guard_contexts);
    guard_contexts = NULL;
  }
  circuit_build_times_free_timeouts(get_circuit_build_times_mutable());

  if (!layer2_guards) {
    return;
  }

  SMARTLIST_FOREACH_BEGIN(layer2_guards, layer2_guard_t *, g) {
    layer2_guard_free(g);
  } SMARTLIST_FOREACH_END(g);

  smartlist_free(layer2_guards);
  routerset_free(layer2_routerset);
}