1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
|
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Package ipnlocal is the heart of the Tailscale node agent that controls
// all the other misc pieces of the Tailscale node.
package ipnlocal
import (
"bufio"
"cmp"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand/v2"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"go4.org/mem"
"go4.org/netipx"
"golang.org/x/net/dns/dnsmessage"
"tailscale.com/appc"
"tailscale.com/client/tailscale/apitype"
"tailscale.com/control/controlclient"
"tailscale.com/control/controlknobs"
"tailscale.com/drive"
"tailscale.com/envknob"
"tailscale.com/envknob/featureknob"
"tailscale.com/feature"
"tailscale.com/feature/buildfeatures"
"tailscale.com/health"
"tailscale.com/health/healthmsg"
"tailscale.com/hostinfo"
"tailscale.com/ipn"
"tailscale.com/ipn/conffile"
"tailscale.com/ipn/ipnauth"
"tailscale.com/ipn/ipnext"
"tailscale.com/ipn/ipnstate"
"tailscale.com/log/sockstatlog"
"tailscale.com/logpolicy"
"tailscale.com/net/dns"
"tailscale.com/net/dnscache"
"tailscale.com/net/dnsfallback"
"tailscale.com/net/ipset"
"tailscale.com/net/netcheck"
"tailscale.com/net/netkernelconf"
"tailscale.com/net/netmon"
"tailscale.com/net/netns"
"tailscale.com/net/netutil"
"tailscale.com/net/packet"
"tailscale.com/net/tsaddr"
"tailscale.com/net/tsdial"
"tailscale.com/paths"
"tailscale.com/syncs"
"tailscale.com/tailcfg"
"tailscale.com/tsd"
"tailscale.com/tstime"
"tailscale.com/types/appctype"
"tailscale.com/types/dnstype"
"tailscale.com/types/empty"
"tailscale.com/types/key"
"tailscale.com/types/logger"
"tailscale.com/types/logid"
"tailscale.com/types/netmap"
"tailscale.com/types/opt"
"tailscale.com/types/persist"
"tailscale.com/types/preftype"
"tailscale.com/types/views"
"tailscale.com/util/checkchange"
"tailscale.com/util/clientmetric"
"tailscale.com/util/dnsname"
"tailscale.com/util/eventbus"
"tailscale.com/util/execqueue"
"tailscale.com/util/goroutines"
"tailscale.com/util/mak"
"tailscale.com/util/osuser"
"tailscale.com/util/rands"
"tailscale.com/util/set"
"tailscale.com/util/slicesx"
"tailscale.com/util/syspolicy/pkey"
"tailscale.com/util/syspolicy/policyclient"
"tailscale.com/util/syspolicy/ptype"
"tailscale.com/util/testenv"
"tailscale.com/util/usermetric"
"tailscale.com/util/vizerror"
"tailscale.com/version"
"tailscale.com/version/distro"
"tailscale.com/wgengine"
"tailscale.com/wgengine/filter"
"tailscale.com/wgengine/magicsock"
"tailscale.com/wgengine/router"
"tailscale.com/wgengine/wgcfg"
"tailscale.com/wgengine/wgcfg/nmcfg"
)
var controlDebugFlags = getControlDebugFlags()
func getControlDebugFlags() []string {
if e := envknob.String("TS_DEBUG_CONTROL_FLAGS"); e != "" {
return strings.Split(e, ",")
}
return nil
}
// SSHServer is the interface of the conditionally linked ssh/tailssh.server.
type SSHServer interface {
HandleSSHConn(net.Conn) error
// NumActiveConns returns the number of connections passed to HandleSSHConn
// that are still active.
NumActiveConns() int
// OnPolicyChange is called when the SSH access policy changes,
// so that existing sessions can be re-evaluated for validity
// and closed if they'd no longer be accepted.
OnPolicyChange()
// Shutdown is called when tailscaled is shutting down.
Shutdown()
}
type newSSHServerFunc func(logger.Logf, *LocalBackend) (SSHServer, error)
var newSSHServer newSSHServerFunc // or nil
// RegisterNewSSHServer lets the conditionally linked ssh/tailssh package register itself.
func RegisterNewSSHServer(fn newSSHServerFunc) {
newSSHServer = fn
}
// watchSession represents a WatchNotifications channel,
// an [ipnauth.Actor] that owns it (e.g., a connected GUI/CLI),
// and sessionID as required to close targeted buses.
type watchSession struct {
ch chan *ipn.Notify
owner ipnauth.Actor // or nil
sessionID string
cancel context.CancelFunc // to shut down the session
mask ipn.NotifyWatchOpt // watch options for this session
}
var (
// errShutdown indicates that the [LocalBackend.Shutdown] was called.
errShutdown = errors.New("shutting down")
// errNodeContextChanged indicates that [LocalBackend] has switched
// to a different [localNodeContext], usually due to a profile change.
// It is used as a context cancellation cause for the old context
// and can be returned when an operation is performed on it.
errNodeContextChanged = errors.New("profile changed")
// errManagedByPolicy indicates the operation is blocked
// because the target state is managed by a GP/MDM policy.
errManagedByPolicy = errors.New("managed by policy")
// ErrProfileStorageUnavailable indicates that profile-specific local data
// storage is not available; see [LocalBackend.ProfileMkdirAll].
ErrProfileStorageUnavailable = errors.New("profile local data storage unavailable")
)
// LocalBackend is the glue between the major pieces of the Tailscale
// network software: the cloud control plane (via controlclient), the
// network data plane (via wgengine), and the user-facing UIs and CLIs
// (collectively called "frontends", via LocalBackend's implementation
// of the Backend interface).
//
// LocalBackend implements the overall state machine for the Tailscale
// application. Frontends, controlclient and wgengine can feed events
// into LocalBackend to advance the state machine, and advancing the
// state machine generates events back out to zero or more components.
type LocalBackend struct {
// Elements that are thread-safe or constant after construction.
ctx context.Context // canceled by [LocalBackend.Shutdown]
ctxCancel context.CancelCauseFunc // cancels ctx
logf logger.Logf // general logging
keyLogf logger.Logf // for printing list of peers on change
statsLogf logger.Logf // for printing peers stats on change
sys *tsd.System
eventClient *eventbus.Client
appcTask execqueue.ExecQueue // handles updates from appc
health *health.Tracker // always non-nil
polc policyclient.Client // always non-nil
metrics metrics
e wgengine.Engine // non-nil; TODO(bradfitz): remove; use sys
store ipn.StateStore // non-nil; TODO(bradfitz): remove; use sys
dialer *tsdial.Dialer // non-nil; TODO(bradfitz): remove; use sys
pushDeviceToken syncs.AtomicValue[string]
backendLogID logid.PublicID // or zero value if logging not in use
unregisterSysPolicyWatch func()
varRoot string // or empty if SetVarRoot never called
logFlushFunc func() // or nil if SetLogFlusher wasn't called
em *expiryManager // non-nil; TODO(nickkhyl): move to nodeBackend
sshAtomicBool atomic.Bool // TODO(nickkhyl): move to nodeBackend
// webClientAtomicBool controls whether the web client is running. This should
// be true unless the disable-web-client node attribute has been set.
webClientAtomicBool atomic.Bool // TODO(nickkhyl): move to nodeBackend
// exposeRemoteWebClientAtomicBool controls whether the web client is exposed over
// Tailscale on port 5252.
exposeRemoteWebClientAtomicBool atomic.Bool // TODO(nickkhyl): move to nodeBackend
shutdownCalled bool // if Shutdown has been called
debugSink packet.CaptureSink
sockstatLogger *sockstatlog.Logger
// getTCPHandlerForFunnelFlow returns a handler for an incoming TCP flow for
// the provided srcAddr and dstPort if one exists.
//
// srcAddr is the source address of the flow, not the address of the Funnel
// node relaying the flow.
// dstPort is the destination port of the flow.
//
// It returns nil if there is no known handler for this flow.
//
// This is specifically used to handle TCP flows for Funnel connections to tsnet
// servers.
//
// It is set once during initialization, and can be nil if SetTCPHandlerForFunnelFlow
// is never called.
getTCPHandlerForFunnelFlow func(srcAddr netip.AddrPort, dstPort uint16) (handler func(net.Conn))
containsViaIPFuncAtomic syncs.AtomicValue[func(netip.Addr) bool] // TODO(nickkhyl): move to nodeBackend
shouldInterceptTCPPortAtomic syncs.AtomicValue[func(uint16) bool] // TODO(nickkhyl): move to nodeBackend
shouldInterceptVIPServicesTCPPortAtomic syncs.AtomicValue[func(netip.AddrPort) bool] // TODO(nickkhyl): move to nodeBackend
numClientStatusCalls atomic.Uint32 // TODO(nickkhyl): move to nodeBackend
// goTracker accounts for all goroutines started by LocalBacked, primarily
// for testing and graceful shutdown purposes.
goTracker goroutines.Tracker
startOnce sync.Once // protects the one‑time initialization in [LocalBackend.Start]
// extHost is the bridge between [LocalBackend] and the registered [ipnext.Extension]s.
// It may be nil in tests that use direct composite literal initialization of [LocalBackend]
// instead of calling [NewLocalBackend]. A nil pointer is a valid, no-op host.
// It can be used with or without b.mu held, but is typically used with it held
// to prevent state changes while invoking callbacks.
extHost *ExtensionHost
peerAPIPorts syncs.AtomicValue[map[netip.Addr]int] // can be read without b.mu held; TODO(nickkhyl): remove or move to nodeBackend?
// The mutex protects the following elements.
mu syncs.Mutex
// currentNodeAtomic is the current node context. It is always non-nil.
// It must be re-created when [LocalBackend] switches to a different profile/node
// (see tailscale/corp#28014 for a bug), but can be mutated in place (via its methods)
// while [LocalBackend] represents the same node.
//
// It is safe for reading with or without holding b.mu, but mutating it in place
// or creating a new one must be done with b.mu held. If both mutexes must be held,
// the LocalBackend's mutex must be acquired first before acquiring the nodeBackend's mutex.
//
// We intend to relax this in the future and only require holding b.mu when replacing it,
// but that requires a better (strictly ordered?) state machine and better management
// of [LocalBackend]'s own state that is not tied to the node context.
currentNodeAtomic atomic.Pointer[nodeBackend]
diskCache diskCache
conf *conffile.Config // latest parsed config, or nil if not in declarative mode
pm *profileManager // mu guards access
lastFilterInputs *filterInputs
httpTestClient *http.Client // for controlclient. nil by default, used by tests.
ccGen clientGen // function for producing controlclient; lazily populated
sshServer SSHServer // or nil, initialized lazily.
appConnector *appc.AppConnector // or nil, initialized when configured.
// notifyCancel cancels notifications to the current SetNotifyCallback.
notifyCancel context.CancelFunc
cc controlclient.Client // TODO(nickkhyl): move to nodeBackend
ccAuto *controlclient.Auto // if cc is of type *controlclient.Auto; TODO(nickkhyl): move to nodeBackend
// ignoreControlClientUpdates indicates whether we want to ignore SetControlClientStatus updates
// before acquiring b.mu. This is used during shutdown to avoid deadlocks.
ignoreControlClientUpdates atomic.Bool
machinePrivKey key.MachinePrivate
tka *tkaState // TODO(nickkhyl): move to nodeBackend
state ipn.State // TODO(nickkhyl): move to nodeBackend
capTailnetLock bool // whether netMap contains the tailnet lock capability
// hostinfo is mutated in-place while mu is held.
hostinfo *tailcfg.Hostinfo // TODO(nickkhyl): move to nodeBackend
nmExpiryTimer tstime.TimerController // for updating netMap on node expiry; can be nil; TODO(nickkhyl): move to nodeBackend
activeLogin string // last logged LoginName from netMap; TODO(nickkhyl): move to nodeBackend (or remove? it's in [ipn.LoginProfile]).
engineStatus ipn.EngineStatus
endpoints []tailcfg.Endpoint
blocked bool
keyExpired bool // TODO(nickkhyl): move to nodeBackend
authURL string // non-empty if not Running; TODO(nickkhyl): move to nodeBackend
authURLTime time.Time // when the authURL was received from the control server; TODO(nickkhyl): move to nodeBackend
authActor ipnauth.Actor // an actor who called [LocalBackend.StartLoginInteractive] last, or nil; TODO(nickkhyl): move to nodeBackend
egg bool
interfaceState *netmon.State // latest network interface state or nil
peerAPIServer *peerAPIServer // or nil
peerAPIListeners []*peerAPIListener // TODO(nickkhyl): move to nodeBackend
loginFlags controlclient.LoginFlags
notifyWatchers map[string]*watchSession // by session ID
lastStatusTime time.Time // status.AsOf value of the last processed status update
componentLogUntil map[string]componentLogState
currentUser ipnauth.Actor
// capForcedNetfilter is the netfilter that control instructs Linux clients
// to use, unless overridden locally.
capForcedNetfilter string // TODO(nickkhyl): move to nodeBackend
// ServeConfig fields. (also guarded by mu)
lastServeConfJSON mem.RO // last JSON that was parsed into serveConfig
serveConfig ipn.ServeConfigView // or !Valid if none
ipVIPServiceMap netmap.IPServiceMappings // map of VIPService IPs to their corresponding service names; TODO(nickkhyl): move to nodeBackend
webClient webClient
webClientListeners map[netip.AddrPort]*localListener // listeners for local web client traffic
serveListeners map[netip.AddrPort]*localListener // listeners for local serve traffic
serveProxyHandlers sync.Map // string (HTTPHandler.Proxy) => *reverseProxy
// dialPlan is any dial plan that we've received from the control
// server during a previous connection; it is cleared on logout.
dialPlan atomic.Pointer[tailcfg.ControlDialPlan] // TODO(nickkhyl): maybe move to nodeBackend?
// tkaSyncLock is used to make tkaSyncIfNeeded an exclusive
// section. This is needed to stop two map-responses in quick succession
// from racing each other through TKA sync logic / RPCs.
//
// tkaSyncLock MUST be taken before mu (or inversely, mu must not be held
// at the moment that tkaSyncLock is taken).
tkaSyncLock syncs.Mutex
clock tstime.Clock
// Last ClientVersion received in MapResponse, guarded by mu.
lastClientVersion *tailcfg.ClientVersion
// lastNotifiedDriveSharesMu guards lastNotifiedDriveShares
lastNotifiedDriveSharesMu syncs.Mutex
// lastNotifiedDriveShares keeps track of the last set of shares that we
// notified about.
lastNotifiedDriveShares *views.SliceView[*drive.Share, drive.ShareView]
// lastSuggestedExitNode stores the last suggested exit node suggestion to
// avoid unnecessary churn between multiple equally-good options.
lastSuggestedExitNode tailcfg.StableNodeID
// allowedSuggestedExitNodes is a set of exit nodes permitted by the most recent
// [pkey.AllowedSuggestedExitNodes] value. The allowedSuggestedExitNodesMu
// mutex guards access to this set.
allowedSuggestedExitNodesMu sync.Mutex
allowedSuggestedExitNodes set.Set[tailcfg.StableNodeID]
// refreshAutoExitNode indicates if the exit node should be recomputed when the next netcheck report is available.
refreshAutoExitNode bool // guarded by mu
// captiveCtx and captiveCancel are used to control captive portal
// detection. They are protected by 'mu' and can be changed during the
// lifetime of a LocalBackend.
//
// captiveCtx will always be non-nil, though it might be a canceled
// context. captiveCancel is non-nil if checkCaptivePortalLoop is
// running, and is set to nil after being canceled.
captiveCtx context.Context
captiveCancel context.CancelFunc
// needsCaptiveDetection is a channel that is used to signal either
// that captive portal detection is required (sending true) or that the
// backend is healthy and captive portal detection is not required
// (sending false).
needsCaptiveDetection chan bool
// overrideAlwaysOn is whether [pkey.AlwaysOn] is overridden by the user
// and should have no impact on the WantRunning state until the policy changes,
// or the user re-connects manually, switches to a different profile, etc.
// Notably, this is true when [pkey.AlwaysOnOverrideWithReason] is enabled,
// and the user has disconnected with a reason.
// See tailscale/corp#26146.
overrideAlwaysOn bool
// reconnectTimer is used to schedule a reconnect by setting [ipn.Prefs.WantRunning]
// to true after a delay, or nil if no reconnect is scheduled.
reconnectTimer tstime.TimerController
// overrideExitNodePolicy is whether the user has overridden the exit node policy
// by manually selecting an exit node, as allowed by [pkey.AllowExitNodeOverride].
//
// If true, the [pkey.ExitNodeID] and [pkey.ExitNodeIP] policy settings are ignored,
// and the suggested exit node is not applied automatically.
//
// It is cleared when the user switches back to the state required by policy (typically, auto:any),
// or when switching profiles, connecting/disconnecting Tailscale, restarting the client,
// or on similar events.
//
// See tailscale/corp#29969.
overrideExitNodePolicy bool
// hardwareAttested is whether backend should use a hardware-backed key to
// bind the node identity to this device.
hardwareAttested atomic.Bool
// getCertForTest is used to retrieve TLS certificates in tests.
// See [LocalBackend.ConfigureCertsForTest].
getCertForTest func(hostname string) (*TLSCertKeyPair, error)
// existsPendingAuthReconfig tracks if a goroutine is waiting to
// acquire [LocalBackend]'s mutex inside of [LocalBackend.AuthReconfig].
// It is used to prevent goroutines from piling up to do the same
// work of [LocalBackend.authReconfigLocked].
existsPendingAuthReconfig atomic.Bool
}
// SetHardwareAttested enables hardware attestation key signatures in map
// requests, if supported on this platform. SetHardwareAttested should be called
// before Start.
func (b *LocalBackend) SetHardwareAttested() {
b.hardwareAttested.Store(true)
}
// HardwareAttested reports whether hardware-backed attestation keys should be
// used to bind the node's identity to this device.
func (b *LocalBackend) HardwareAttested() bool {
return b.hardwareAttested.Load()
}
// HealthTracker returns the health tracker for the backend.
func (b *LocalBackend) HealthTracker() *health.Tracker { return b.health }
// Logger returns the logger for the backend.
func (b *LocalBackend) Logger() logger.Logf { return b.logf }
// UserMetricsRegistry returns the usermetrics registry for the backend
func (b *LocalBackend) UserMetricsRegistry() *usermetric.Registry {
return b.sys.UserMetricsRegistry()
}
// NetMon returns the network monitor for the backend.
func (b *LocalBackend) NetMon() *netmon.Monitor {
return b.sys.NetMon.Get()
}
// PolicyClient returns the policy client for the backend.
func (b *LocalBackend) PolicyClient() policyclient.Client { return b.polc }
type metrics struct {
// advertisedRoutes is a metric that reports the number of network routes that are advertised by the local node.
// This informs the user of how many routes are being advertised by the local node, excluding exit routes.
advertisedRoutes *usermetric.Gauge
// approvedRoutes is a metric that reports the number of network routes served by the local node and approved
// by the control server.
approvedRoutes *usermetric.Gauge
}
// clientGen is a func that creates a control plane client.
// It's the type used by LocalBackend.SetControlClientGetterForTesting.
type clientGen func(controlclient.Options) (controlclient.Client, error)
// NewLocalBackend returns a new LocalBackend that is ready to run,
// but is not actually running.
//
// If dialer is nil, a new one is made.
//
// The logID may be the zero value if logging is not in use.
func NewLocalBackend(logf logger.Logf, logID logid.PublicID, sys *tsd.System, loginFlags controlclient.LoginFlags) (_ *LocalBackend, err error) {
e := sys.Engine.Get()
store := sys.StateStore.Get()
dialer := sys.Dialer.Get()
if dialer == nil {
return nil, errors.New("dialer to NewLocalBackend must be set")
}
if dialer.NetMon() == nil {
return nil, errors.New("dialer to NewLocalBackend must have a NetMon")
}
mConn := sys.MagicSock.Get()
goos := envknob.GOOS()
if loginFlags&controlclient.LocalBackendStartKeyOSNeutral != 0 {
goos = ""
}
pm, err := newProfileManagerWithGOOS(store, logf, sys.HealthTracker.Get(), goos)
if err != nil {
return nil, err
}
if sds, ok := store.(ipn.StateStoreDialerSetter); ok {
sds.SetDialer(dialer.SystemDial)
}
envknob.LogCurrent(logf)
ctx, cancel := context.WithCancelCause(context.Background())
clock := tstime.StdClock{}
// Until we transition to a Running state, use a canceled context for
// our captive portal detection.
captiveCtx, captiveCancel := context.WithCancel(ctx)
captiveCancel()
m := metrics{
advertisedRoutes: sys.UserMetricsRegistry().NewGauge(
"tailscaled_advertised_routes", "Number of advertised network routes (e.g. by a subnet router)"),
approvedRoutes: sys.UserMetricsRegistry().NewGauge(
"tailscaled_approved_routes", "Number of approved network routes (e.g. by a subnet router)"),
}
b := &LocalBackend{
ctx: ctx,
ctxCancel: cancel,
logf: logf,
keyLogf: logger.LogOnChange(logf, 5*time.Minute, clock.Now),
statsLogf: logger.LogOnChange(logf, 5*time.Minute, clock.Now),
sys: sys,
polc: sys.PolicyClientOrDefault(),
health: sys.HealthTracker.Get(),
metrics: m,
e: e,
dialer: dialer,
store: store,
pm: pm,
backendLogID: logID,
state: ipn.NoState,
em: newExpiryManager(logf, sys.Bus.Get()),
loginFlags: loginFlags,
clock: clock,
captiveCtx: captiveCtx,
captiveCancel: nil, // so that we start checkCaptivePortalLoop when Running
needsCaptiveDetection: make(chan bool),
}
nb := newNodeBackend(ctx, b.logf, b.sys.Bus.Get())
b.currentNodeAtomic.Store(nb)
nb.ready()
if sys.InitialConfig != nil {
if err := b.initPrefsFromConfig(sys.InitialConfig); err != nil {
return nil, err
}
}
if b.extHost, err = NewExtensionHost(logf, b); err != nil {
return nil, fmt.Errorf("failed to create extension host: %w", err)
}
b.pm.SetExtensionHost(b.extHost)
if b.unregisterSysPolicyWatch, err = b.registerSysPolicyWatch(); err != nil {
return nil, err
}
defer func() {
if err != nil {
b.unregisterSysPolicyWatch()
}
}()
netMon := sys.NetMon.Get()
b.sockstatLogger, err = sockstatlog.NewLogger(logpolicy.LogsDir(logf), logf, logID, netMon, sys.HealthTracker.Get(), sys.Bus.Get())
if err != nil {
logf("error setting up sockstat logger: %v", err)
}
// Enable sockstats logs only on non-mobile unstable builds
if version.IsUnstableBuild() && !version.IsMobile() && b.sockstatLogger != nil {
b.sockstatLogger.SetLoggingEnabled(true)
}
// Default filter blocks everything and logs nothing, until Start() is called.
noneFilter := filter.NewAllowNone(logf, &netipx.IPSet{})
b.setFilter(noneFilter)
b.e.SetJailedFilter(noneFilter)
b.setTCPPortsIntercepted(nil)
b.e.SetStatusCallback(b.setWgengineStatus)
b.interfaceState = netMon.InterfaceState()
// Call our linkChange code once with the current state.
// Following changes are triggered via the eventbus.
cd, err := netmon.NewChangeDelta(nil, b.interfaceState, 0, false)
if err != nil {
b.logf("[unexpected] setting initial netmon state failed: %v", err)
} else {
b.linkChange(cd)
}
if buildfeatures.HasPeerAPIServer {
if tunWrap, ok := b.sys.Tun.GetOK(); ok {
tunWrap.PeerAPIPort = b.GetPeerAPIPort
} else {
b.logf("[unexpected] failed to wire up PeerAPI port for engine %T", e)
}
}
if buildfeatures.HasDebug {
for _, component := range ipn.DebuggableComponents {
key := componentStateKey(component)
if ut, err := ipn.ReadStoreInt(pm.Store(), key); err == nil {
if until := time.Unix(ut, 0); until.After(b.clock.Now()) {
// conditional to avoid log spam at start when off
b.SetComponentDebugLogging(component, until)
}
}
}
}
// Start the event bus late, once all the assignments above are done.
// (See previous race in tailscale/tailscale#17252)
ec := b.Sys().Bus.Get().Client("ipnlocal.LocalBackend")
b.eventClient = ec
eventbus.SubscribeFunc(ec, b.onClientVersion)
eventbus.SubscribeFunc(ec, func(au controlclient.AutoUpdate) {
b.onTailnetDefaultAutoUpdate(au.Value)
})
eventbus.SubscribeFunc(ec, func(cd netmon.ChangeDelta) { b.linkChange(&cd) })
if buildfeatures.HasHealth {
eventbus.SubscribeFunc(ec, b.onHealthChange)
}
if buildfeatures.HasPortList {
eventbus.SubscribeFunc(ec, b.setPortlistServices)
}
eventbus.SubscribeFunc(ec, b.onAppConnectorRouteUpdate)
eventbus.SubscribeFunc(ec, b.onAppConnectorStoreRoutes)
mConn.SetNetInfoCallback(b.setNetInfo) // TODO(tailscale/tailscale#17887): move to eventbus
return b, nil
}
func (b *LocalBackend) onAppConnectorRouteUpdate(ru appctype.RouteUpdate) {
// TODO(creachadair, 2025-10-02): It is currently possible for updates produced under
// one profile to arrive and be applied after a switch to another profile.
// We need to find a way to ensure that changes to the backend state are applied
// consistently in the presnce of profile changes, which currently may not happen in
// a single atomic step. See: https://github.com/tailscale/tailscale/issues/17414
b.appcTask.Add(func() {
if err := b.AdvertiseRoute(ru.Advertise...); err != nil {
b.logf("appc: failed to advertise routes: %v: %v", ru.Advertise, err)
}
if err := b.UnadvertiseRoute(ru.Unadvertise...); err != nil {
b.logf("appc: failed to unadvertise routes: %v: %v", ru.Unadvertise, err)
}
})
}
func (b *LocalBackend) onAppConnectorStoreRoutes(ri appctype.RouteInfo) {
// Whether or not routes should be stored can change over time.
shouldStoreRoutes := b.ControlKnobs().AppCStoreRoutes.Load()
if shouldStoreRoutes {
if err := b.storeRouteInfo(ri); err != nil {
b.logf("appc: failed to store route info: %v", err)
}
}
}
func (b *LocalBackend) Clock() tstime.Clock { return b.clock }
func (b *LocalBackend) Sys() *tsd.System { return b.sys }
// NodeBackend returns the current node's NodeBackend interface.
func (b *LocalBackend) NodeBackend() ipnext.NodeBackend {
return b.currentNode()
}
func (b *LocalBackend) currentNode() *nodeBackend {
if v := b.currentNodeAtomic.Load(); v != nil || !testenv.InTest() {
return v
}
v := newNodeBackend(cmp.Or(b.ctx, context.Background()), b.logf, b.sys.Bus.Get())
if b.currentNodeAtomic.CompareAndSwap(nil, v) {
v.ready()
}
return b.currentNodeAtomic.Load()
}
// FindExtensionByName returns an active extension with the given name,
// or nil if no such extension exists.
func (b *LocalBackend) FindExtensionByName(name string) any {
return b.extHost.Extensions().FindExtensionByName(name)
}
// FindMatchingExtension finds the first active extension that matches target,
// and if one is found, sets target to that extension and returns true.
// Otherwise, it returns false.
//
// It panics if target is not a non-nil pointer to either a type
// that implements [ipnext.Extension], or to any interface type.
func (b *LocalBackend) FindMatchingExtension(target any) bool {
return b.extHost.Extensions().FindMatchingExtension(target)
}
type componentLogState struct {
until time.Time
timer tstime.TimerController // if non-nil, the AfterFunc to disable it
}
func componentStateKey(component string) ipn.StateKey {
return ipn.StateKey("_debug_" + component + "_until")
}
// SetComponentDebugLogging sets component's debug logging enabled until the until time.
// If until is in the past, the component's debug logging is disabled.
//
// The following components are recognized:
//
// - magicsock
// - sockstats
func (b *LocalBackend) SetComponentDebugLogging(component string, until time.Time) error {
if !buildfeatures.HasDebug {
return feature.ErrUnavailable
}
b.mu.Lock()
defer b.mu.Unlock()
var setEnabled func(bool)
switch component {
case "magicsock":
setEnabled = b.MagicConn().SetDebugLoggingEnabled
case "sockstats":
if b.sockstatLogger != nil {
setEnabled = func(v bool) {
b.sockstatLogger.SetLoggingEnabled(v)
// Flush (and thus upload) logs when the enabled period ends,
// so that the logs are available for debugging.
if !v {
b.sockstatLogger.Flush()
}
}
}
case "syspolicy":
setEnabled = b.polc.SetDebugLoggingEnabled
}
if setEnabled == nil || !slices.Contains(ipn.DebuggableComponents, component) {
return fmt.Errorf("unknown component %q", component)
}
timeUnixOrZero := func(t time.Time) int64 {
if t.IsZero() {
return 0
}
return t.Unix()
}
ipn.PutStoreInt(b.store, componentStateKey(component), timeUnixOrZero(until))
now := b.clock.Now()
on := now.Before(until)
setEnabled(on)
var onFor time.Duration
if on {
onFor = until.Sub(now)
b.logf("debugging logging for component %q enabled for %v (until %v)", component, onFor.Round(time.Second), until.UTC().Format(time.RFC3339))
} else {
b.logf("debugging logging for component %q disabled", component)
}
if oldSt, ok := b.componentLogUntil[component]; ok && oldSt.timer != nil {
oldSt.timer.Stop()
}
newSt := componentLogState{until: until}
if on {
newSt.timer = b.clock.AfterFunc(onFor, func() {
// Turn off logging after the timer fires, as long as the state is
// unchanged when the timer actually fires.
b.mu.Lock()
defer b.mu.Unlock()
if ls := b.componentLogUntil[component]; ls.until.Equal(until) {
setEnabled(false)
b.logf("debugging logging for component %q disabled (by timer)", component)
}
})
}
mak.Set(&b.componentLogUntil, component, newSt)
return nil
}
// GetDNSOSConfig returns the base OS DNS configuration, as seen by the DNS manager.
func (b *LocalBackend) GetDNSOSConfig() (dns.OSConfig, error) {
if !buildfeatures.HasDNS {
panic("unreachable")
}
manager, ok := b.sys.DNSManager.GetOK()
if !ok {
return dns.OSConfig{}, errors.New("DNS manager not available")
}
return manager.GetBaseConfig()
}
// QueryDNS performs a DNS query for name and queryType using the built-in DNS resolver, and returns
// the raw DNS response and the resolvers that are were able to handle the query (the internal forwarder
// may race multiple resolvers).
func (b *LocalBackend) QueryDNS(name string, queryType dnsmessage.Type) (res []byte, resolvers []*dnstype.Resolver, err error) {
if !buildfeatures.HasDNS {
return nil, nil, feature.ErrUnavailable
}
manager, ok := b.sys.DNSManager.GetOK()
if !ok {
return nil, nil, errors.New("DNS manager not available")
}
fqdn, err := dnsname.ToFQDN(name)
if err != nil {
b.logf("DNSQuery: failed to parse FQDN %q: %v", name, err)
return nil, nil, err
}
n, err := dnsmessage.NewName(fqdn.WithTrailingDot())
if err != nil {
b.logf("DNSQuery: failed to parse name %q: %v", name, err)
return nil, nil, err
}
from := netip.MustParseAddrPort("127.0.0.1:0")
db := dnsmessage.NewBuilder(nil, dnsmessage.Header{
OpCode: 0,
RecursionDesired: true,
ID: 1,
})
db.StartQuestions()
db.Question(dnsmessage.Question{
Name: n,
Type: queryType,
Class: dnsmessage.ClassINET,
})
q, err := db.Finish()
if err != nil {
b.logf("DNSQuery: failed to build query: %v", err)
return nil, nil, err
}
res, err = manager.Query(b.ctx, q, "tcp", from)
if err != nil {
b.logf("DNSQuery: failed to query %q: %v", name, err)
return nil, nil, err
}
rr := manager.Resolver().GetUpstreamResolvers(fqdn)
return res, rr, nil
}
// GetComponentDebugLogging gets the time that component's debug logging is
// enabled until, or the zero time if component's time is not currently
// enabled.
func (b *LocalBackend) GetComponentDebugLogging(component string) time.Time {
if !buildfeatures.HasDebug {
return time.Time{}
}
b.mu.Lock()
defer b.mu.Unlock()
now := b.clock.Now()
ls := b.componentLogUntil[component]
if ls.until.IsZero() || ls.until.Before(now) {
return time.Time{}
}
return ls.until
}
// Dialer returns the backend's dialer.
// It is always non-nil.
func (b *LocalBackend) Dialer() *tsdial.Dialer {
return b.dialer
}
// ReloadConfig reloads the backend's config from disk.
//
// It returns (false, nil) if not running in declarative mode, (true, nil) on
// success, or (false, error) on failure.
func (b *LocalBackend) ReloadConfig() (ok bool, err error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.conf == nil {
return false, nil
}
conf, err := conffile.Load(b.conf.Path)
if err != nil {
return false, err
}
if err := b.setConfigLocked(conf); err != nil {
return false, fmt.Errorf("error setting config: %w", err)
}
return true, nil
}
// initPrefsFromConfig initializes the backend's prefs from the provided config.
// This should only be called once, at startup. For updates at runtime, use
// [LocalBackend.setConfigLocked].
func (b *LocalBackend) initPrefsFromConfig(conf *conffile.Config) error {
// TODO(maisem,bradfitz): combine this with setConfigLocked. This is called
// before anything is running, so there's no need to lock and we don't
// update any subsystems. At runtime, we both need to lock and update
// subsystems with the new prefs.
p := b.pm.CurrentPrefs().AsStruct()
mp, err := conf.Parsed.ToPrefs()
if err != nil {
return fmt.Errorf("error parsing config to prefs: %w", err)
}
p.ApplyEdits(&mp)
if err := b.pm.SetPrefs(p.View(), ipn.NetworkProfile{}); err != nil {
return err
}
b.updateWarnSync(p.View())
b.setStaticEndpointsFromConfigLocked(conf)
b.conf = conf
return nil
}
func (b *LocalBackend) setStaticEndpointsFromConfigLocked(conf *conffile.Config) {
syncs.RequiresMutex(&b.mu)
if conf.Parsed.StaticEndpoints == nil && (b.conf == nil || b.conf.Parsed.StaticEndpoints == nil) {
return
}
// Ensure that magicsock conn has the up to date static wireguard
// endpoints. Setting the endpoints here triggers an asynchronous update
// of the node's advertised endpoints.
if b.conf == nil && len(conf.Parsed.StaticEndpoints) != 0 || !reflect.DeepEqual(conf.Parsed.StaticEndpoints, b.conf.Parsed.StaticEndpoints) {
ms, ok := b.sys.MagicSock.GetOK()
if !ok {
b.logf("[unexpected] ReloadConfig: MagicSock not set")
} else {
ms.SetStaticEndpoints(views.SliceOf(conf.Parsed.StaticEndpoints))
}
}
}
func (b *LocalBackend) setStateLocked(state ipn.State) {
syncs.RequiresMutex(&b.mu)
if b.state == state {
return
}
b.state = state
for _, f := range b.extHost.Hooks().BackendStateChange {
f(state)
}
}
func (b *LocalBackend) IPServiceMappings() netmap.IPServiceMappings {
b.mu.Lock()
defer b.mu.Unlock()
return b.ipVIPServiceMap
}
func (b *LocalBackend) SetIPServiceMappingsForTest(m netmap.IPServiceMappings) {
b.mu.Lock()
defer b.mu.Unlock()
testenv.AssertInTest()
b.ipVIPServiceMap = m
if ns, ok := b.sys.Netstack.GetOK(); ok {
ns.UpdateIPServiceMappings(m)
}
}
// setConfigLocked uses the provided config to update the backend's prefs
// and other state.
func (b *LocalBackend) setConfigLocked(conf *conffile.Config) error {
syncs.RequiresMutex(&b.mu)
p := b.pm.CurrentPrefs().AsStruct()
mp, err := conf.Parsed.ToPrefs()
if err != nil {
return fmt.Errorf("error parsing config to prefs: %w", err)
}
p.ApplyEdits(&mp)
b.setStaticEndpointsFromConfigLocked(conf)
b.setPrefsLocked(p)
b.conf = conf
return nil
}
// pauseOrResumeControlClientLocked pauses b.cc if there is no network available
// or if the LocalBackend is in Stopped state with a valid NetMap. In all other
// cases, it unpauses it. It is a no-op if b.cc is nil.
//
// b.mu must be held.
func (b *LocalBackend) pauseOrResumeControlClientLocked() {
syncs.RequiresMutex(&b.mu)
if b.cc == nil {
return
}
networkUp := b.interfaceState.AnyInterfaceUp()
pauseForNetwork := (b.state == ipn.Stopped && b.NetMap() != nil) || (!networkUp && !testenv.InTest() && !envknob.AssumeNetworkUp())
prefs := b.pm.CurrentPrefs()
pauseForSyncPref := prefs.Valid() && prefs.Sync().EqualBool(false)
b.cc.SetPaused(pauseForNetwork || pauseForSyncPref)
}
// DisconnectControl shuts down control client. This can be run before node shutdown to force control to consider this ndoe
// inactive. This can be used to ensure that nodes that are HA subnet router or app connector replicas are shutting
// down, clients switch over to other replicas whilst the existing connections are kept alive for some period of time.
func (b *LocalBackend) DisconnectControl() {
b.mu.Lock()
cc := b.resetControlClientLocked()
b.mu.Unlock()
if cc != nil {
cc.Shutdown()
}
}
// linkChange is our network monitor callback, called whenever the network changes.
func (b *LocalBackend) linkChange(delta *netmon.ChangeDelta) {
b.mu.Lock()
defer b.mu.Unlock()
b.interfaceState = delta.CurrentState()
b.pauseOrResumeControlClientLocked()
prefs := b.pm.CurrentPrefs()
if delta.RebindLikelyRequired && prefs.AutoExitNode().IsSet() {
b.refreshAutoExitNode = true
}
var needReconfig bool
// If the network changed and we're using an exit node and allowing LAN access, we may need to reconfigure.
if delta.RebindLikelyRequired && prefs.ExitNodeID() != "" && prefs.ExitNodeAllowLANAccess() {
b.logf("linkChange: in state %v; updating LAN routes", b.state)
needReconfig = true
}
// If the PAC-ness of the network changed, reconfig wireguard+route to add/remove subnets.
if delta.HasPACOrProxyConfigChanged {
b.logf("linkChange: in state %v; PAC or proxyConfig changed; updating routes", b.state)
needReconfig = true
}
if needReconfig {
switch b.state {
case ipn.NoState, ipn.Stopped:
// Do nothing.
default:
// TODO(raggi,tailscale/corp#22574): authReconfig should be refactored such that we can call the
// necessary operations here and avoid the need for asynchronous behavior that is racy and hard
// to test here, and do less extra work in these conditions.
b.goTracker.Go(b.authReconfig)
}
}
// If the local network configuration has changed, our filter may
// need updating to tweak default routes.
b.updateFilterLocked(prefs)
if buildfeatures.HasPeerAPIServer {
cn := b.currentNode()
nm := cn.NetMap()
if peerAPIListenAsync && nm != nil && b.state == ipn.Running {
want := nm.GetAddresses().Len()
have := len(b.peerAPIListeners)
b.logf("[v1] linkChange: have %d peerAPIListeners, want %d", have, want)
if have < want {
b.logf("linkChange: peerAPIListeners too low; trying again")
b.goTracker.Go(b.initPeerAPIListener)
}
}
}
}
// Captive portal detection hooks.
var (
hookCaptivePortalHealthChange feature.Hook[func(*LocalBackend, *health.State)]
hookCheckCaptivePortalLoop feature.Hook[func(*LocalBackend, context.Context)]
)
func (b *LocalBackend) onHealthChange(change health.Change) {
if !buildfeatures.HasHealth {
return
}
if change.WarnableChanged {
w := change.Warnable
us := change.UnhealthyState
if us == nil {
b.logf("health(warnable=%s): ok", w.Code)
} else {
b.logf("health(warnable=%s): error: %s", w.Code, us.Text)
}
}
// Whenever health changes, send the current health state to the frontend.
state := b.health.CurrentState()
b.send(ipn.Notify{
Health: state,
})
// Update control if IP forwarding state changed
_, broken := state.Warnings["ip-forwarding-off"]
b.mu.Lock()
if b.cc != nil {
b.cc.SetIPForwardingBroken(broken)
}
b.mu.Unlock()
if f, ok := hookCaptivePortalHealthChange.GetOk(); ok {
f(b, state)
}
}
// GetOrSetCaptureSink returns the current packet capture sink, creating it
// with the provided newSink function if it does not already exist.
func (b *LocalBackend) GetOrSetCaptureSink(newSink func() packet.CaptureSink) packet.CaptureSink {
if !buildfeatures.HasCapture {
return nil
}
b.mu.Lock()
defer b.mu.Unlock()
if b.debugSink != nil {
return b.debugSink
}
s := newSink()
b.debugSink = s
b.e.InstallCaptureHook(s.CaptureCallback())
return s
}
func (b *LocalBackend) ClearCaptureSink() {
if !buildfeatures.HasCapture {
return
}
// Shut down & uninstall the sink if there are no longer
// any outputs on it.
b.mu.Lock()
defer b.mu.Unlock()
select {
case <-b.ctx.Done():
return
default:
}
if b.debugSink != nil && b.debugSink.NumOutputs() == 0 {
s := b.debugSink
b.e.InstallCaptureHook(nil)
b.debugSink = nil
s.Close()
}
}
// Shutdown halts the backend and all its sub-components. The backend
// can no longer be used after Shutdown returns.
func (b *LocalBackend) Shutdown() {
// Close the [eventbus.Client] to wait for subscribers to
// return before acquiring b.mu:
// 1. Event handlers also acquire b.mu, they can deadlock with c.Shutdown().
// 2. Event handlers may not guard against undesirable post/in-progress
// LocalBackend.Shutdown() behaviors.
b.appcTask.Shutdown()
b.eventClient.Close()
b.em.close()
b.mu.Lock()
if b.shutdownCalled {
b.mu.Unlock()
return
}
b.shutdownCalled = true
if buildfeatures.HasCaptivePortal && b.captiveCancel != nil {
b.logf("canceling captive portal context")
b.captiveCancel()
}
b.stopReconnectTimerLocked()
if b.loginFlags&controlclient.LoginEphemeral != 0 {
b.mu.Unlock()
ctx, cancel := context.WithTimeout(b.ctx, 5*time.Second)
defer cancel()
t0 := time.Now()
err := b.Logout(ctx, ipnauth.Self) // best effort
td := time.Since(t0).Round(time.Millisecond)
if err != nil {
b.logf("failed to log out ephemeral node on shutdown after %v: %v", td, err)
} else {
b.logf("logged out ephemeral node on shutdown")
}
b.mu.Lock()
}
cc := b.cc
if b.sshServer != nil {
b.sshServer.Shutdown()
b.sshServer = nil
}
b.closePeerAPIListenersLocked()
if b.debugSink != nil {
b.e.InstallCaptureHook(nil)
b.debugSink.Close()
b.debugSink = nil
}
if b.notifyCancel != nil {
b.notifyCancel()
}
b.appConnector.Close()
b.mu.Unlock()
b.webClientShutdown()
if b.sockstatLogger != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
b.sockstatLogger.Shutdown(ctx)
}
b.unregisterSysPolicyWatch()
if cc != nil {
cc.Shutdown()
}
b.ctxCancel(errShutdown)
b.currentNode().shutdown(errShutdown)
b.extHost.Shutdown()
b.e.Close()
<-b.e.Done()
b.awaitNoGoroutinesInTest()
}
func (b *LocalBackend) awaitNoGoroutinesInTest() {
if !buildfeatures.HasDebug || !testenv.InTest() {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
ch := make(chan bool, 1)
defer b.goTracker.AddDoneCallback(func() { ch <- true })()
for {
n := b.goTracker.RunningGoroutines()
if n == 0 {
return
}
select {
case <-ctx.Done():
// TODO(bradfitz): pass down some TB-like failer interface from
// tests, without depending on testing from here?
// But this is fine in tests too:
panic(fmt.Sprintf("timeout waiting for %d goroutines to stop", n))
case <-ch:
}
}
}
func stripKeysFromPrefs(p ipn.PrefsView) ipn.PrefsView {
if !p.Valid() || !p.Persist().Valid() {
return p
}
p2 := p.AsStruct()
p2.Persist.PrivateNodeKey = key.NodePrivate{}
p2.Persist.OldPrivateNodeKey = key.NodePrivate{}
p2.Persist.NetworkLockKey = key.NLPrivate{}
p2.Persist.AttestationKey = nil
return p2.View()
}
// Prefs returns a copy of b's current prefs, with any private keys removed.
func (b *LocalBackend) Prefs() ipn.PrefsView {
b.mu.Lock()
defer b.mu.Unlock()
return b.sanitizedPrefsLocked()
}
func (b *LocalBackend) sanitizedPrefsLocked() ipn.PrefsView {
syncs.RequiresMutex(&b.mu)
return stripKeysFromPrefs(b.pm.CurrentPrefs())
}
// unsanitizedPersist returns the current PersistView, including any private keys.
func (b *LocalBackend) unsanitizedPersist() persist.PersistView {
b.mu.Lock()
defer b.mu.Unlock()
return b.pm.CurrentPrefs().Persist()
}
// Status returns the latest status of the backend and its
// sub-components.
func (b *LocalBackend) Status() *ipnstate.Status {
sb := &ipnstate.StatusBuilder{WantPeers: true}
b.UpdateStatus(sb)
return sb.Status()
}
// StatusWithoutPeers is like Status but omits any details
// of peers.
func (b *LocalBackend) StatusWithoutPeers() *ipnstate.Status {
sb := &ipnstate.StatusBuilder{WantPeers: false}
b.UpdateStatus(sb)
return sb.Status()
}
// UpdateStatus implements ipnstate.StatusUpdater.
func (b *LocalBackend) UpdateStatus(sb *ipnstate.StatusBuilder) {
b.e.UpdateStatus(sb) // does wireguard + magicsock status
b.mu.Lock()
defer b.mu.Unlock()
cn := b.currentNode()
nm := cn.NetMap()
sb.MutateStatus(func(s *ipnstate.Status) {
s.Version = version.Long()
s.TUN = !b.sys.IsNetstack()
s.BackendState = b.state.String()
s.AuthURL = b.authURL
if prefs := b.pm.CurrentPrefs(); prefs.Valid() && prefs.AutoUpdate().Check {
s.ClientVersion = b.lastClientVersion
}
s.Health = b.health.Strings()
s.HaveNodeKey = b.hasNodeKeyLocked()
// TODO(bradfitz): move this health check into a health.Warnable
// and remove from here.
if m := b.sshOnButUnusableHealthCheckMessageLocked(); m != "" {
s.Health = append(s.Health, m)
}
if nm != nil {
s.CertDomains = append([]string(nil), nm.DNS.CertDomains...)
s.MagicDNSSuffix = nm.MagicDNSSuffix()
if s.CurrentTailnet == nil {
s.CurrentTailnet = &ipnstate.TailnetStatus{}
}
s.CurrentTailnet.MagicDNSSuffix = nm.MagicDNSSuffix()
s.CurrentTailnet.MagicDNSEnabled = nm.DNS.Proxied
s.CurrentTailnet.Name = nm.Domain
if prefs := b.pm.CurrentPrefs(); prefs.Valid() {
if !prefs.RouteAll() && nm.AnyPeersAdvertiseRoutes() {
s.Health = append(s.Health, healthmsg.WarnAcceptRoutesOff)
}
if !prefs.ExitNodeID().IsZero() {
if exitPeer, ok := nm.PeerWithStableID(prefs.ExitNodeID()); ok {
s.ExitNodeStatus = &ipnstate.ExitNodeStatus{
ID: prefs.ExitNodeID(),
Online: exitPeer.Online().Get(),
TailscaleIPs: exitPeer.Addresses().AsSlice(),
}
}
}
}
}
})
var tailscaleIPs []netip.Addr
if nm != nil {
addrs := nm.GetAddresses()
for i := range addrs.Len() {
if addr := addrs.At(i); addr.IsSingleIP() {
sb.AddTailscaleIP(addr.Addr())
tailscaleIPs = append(tailscaleIPs, addr.Addr())
}
}
}
sb.MutateSelfStatus(func(ss *ipnstate.PeerStatus) {
ss.OS = version.OS()
ss.Online = b.health.GetInPollNetMap()
if nm != nil {
ss.InNetworkMap = true
if hi := nm.SelfNode.Hostinfo(); hi.Valid() {
ss.HostName = hi.Hostname()
}
ss.DNSName = nm.SelfName()
ss.UserID = nm.User()
if sn := nm.SelfNode; sn.Valid() {
peerStatusFromNode(ss, sn)
if cm := sn.CapMap(); cm.Len() > 0 {
ss.Capabilities = make([]tailcfg.NodeCapability, 1, cm.Len()+1)
ss.Capabilities[0] = "HTTPS://TAILSCALE.COM/s/DEPRECATED-NODE-CAPS#see-https://github.com/tailscale/tailscale/issues/11508"
ss.CapMap = make(tailcfg.NodeCapMap, sn.CapMap().Len())
for k, v := range cm.All() {
ss.CapMap[k] = v.AsSlice()
ss.Capabilities = append(ss.Capabilities, k)
}
slices.Sort(ss.Capabilities[1:])
}
}
for _, addr := range tailscaleIPs {
ss.TailscaleIPs = append(ss.TailscaleIPs, addr)
}
} else {
ss.HostName, _ = hostinfo.Hostname()
}
for _, pln := range b.peerAPIListeners {
ss.PeerAPIURL = append(ss.PeerAPIURL, pln.urlStr)
}
})
// TODO: hostinfo, and its networkinfo
// TODO: EngineStatus copy (and deprecate it?)
if sb.WantPeers {
b.populatePeerStatusLocked(sb)
}
}
func (b *LocalBackend) populatePeerStatusLocked(sb *ipnstate.StatusBuilder) {
syncs.RequiresMutex(&b.mu)
cn := b.currentNode()
nm := cn.NetMap()
if nm == nil {
return
}
for id, up := range nm.UserProfiles {
sb.AddUser(id, up)
}
exitNodeID := b.pm.CurrentPrefs().ExitNodeID()
for _, p := range cn.Peers() {
tailscaleIPs := make([]netip.Addr, 0, p.Addresses().Len())
for i := range p.Addresses().Len() {
addr := p.Addresses().At(i)
if addr.IsSingleIP() && tsaddr.IsTailscaleIP(addr.Addr()) {
tailscaleIPs = append(tailscaleIPs, addr.Addr())
}
}
ps := &ipnstate.PeerStatus{
InNetworkMap: true,
UserID: p.User(),
AltSharerUserID: p.Sharer(),
TailscaleIPs: tailscaleIPs,
HostName: p.Hostinfo().Hostname(),
DNSName: p.Name(),
OS: p.Hostinfo().OS(),
LastSeen: p.LastSeen().Get(),
Online: p.Online().Get(),
ShareeNode: p.Hostinfo().ShareeNode(),
ExitNode: p.StableID() != "" && p.StableID() == exitNodeID,
SSH_HostKeys: p.Hostinfo().SSH_HostKeys().AsSlice(),
Location: p.Hostinfo().Location().AsStruct(),
Capabilities: p.Capabilities().AsSlice(),
}
for _, f := range b.extHost.Hooks().SetPeerStatus {
f(ps, p, cn)
}
if cm := p.CapMap(); cm.Len() > 0 {
ps.CapMap = make(tailcfg.NodeCapMap, cm.Len())
for k, v := range cm.All() {
ps.CapMap[k] = v.AsSlice()
}
}
peerStatusFromNode(ps, p)
p4, p6 := peerAPIPorts(p)
if u := peerAPIURL(nodeIP(p, netip.Addr.Is4), p4); u != "" {
ps.PeerAPIURL = append(ps.PeerAPIURL, u)
}
if u := peerAPIURL(nodeIP(p, netip.Addr.Is6), p6); u != "" {
ps.PeerAPIURL = append(ps.PeerAPIURL, u)
}
sb.AddPeer(p.Key(), ps)
}
}
// peerStatusFromNode copies fields that exist in the Node struct for
// current node and peers into the provided PeerStatus.
func peerStatusFromNode(ps *ipnstate.PeerStatus, n tailcfg.NodeView) {
ps.PublicKey = n.Key()
ps.ID = n.StableID()
ps.Created = n.Created()
ps.ExitNodeOption = buildfeatures.HasUseExitNode && tsaddr.ContainsExitRoutes(n.AllowedIPs())
if n.Tags().Len() != 0 {
v := n.Tags()
ps.Tags = &v
}
if n.PrimaryRoutes().Len() != 0 {
v := n.PrimaryRoutes()
ps.PrimaryRoutes = &v
}
if n.AllowedIPs().Len() != 0 {
v := n.AllowedIPs()
ps.AllowedIPs = &v
}
if n.Expired() {
ps.Expired = true
}
if t := n.KeyExpiry(); !t.IsZero() {
t = t.Round(time.Second)
ps.KeyExpiry = &t
}
}
func profileFromView(v tailcfg.UserProfileView) tailcfg.UserProfile {
if v.Valid() {
return tailcfg.UserProfile{
ID: v.ID(),
LoginName: v.LoginName(),
DisplayName: v.DisplayName(),
ProfilePicURL: v.ProfilePicURL(),
Groups: v.Groups().AsSlice(),
}
}
return tailcfg.UserProfile{}
}
// WhoIsNodeKey returns the peer info of given public key, if it exists.
func (b *LocalBackend) WhoIsNodeKey(k key.NodePublic) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool) {
cn := b.currentNode()
if nid, ok := cn.NodeByKey(k); ok {
if n, ok := cn.NodeByID(nid); ok {
up, ok := cn.NetMap().UserProfiles[n.User()]
u = profileFromView(up)
return n, u, ok
}
}
return n, u, false
}
var debugWhoIs = envknob.RegisterBool("TS_DEBUG_WHOIS")
// WhoIs reports the node and user who owns the node with the given IP:port.
// If the IP address is a Tailscale IP, the provided port may be 0.
//
// The 'proto' is used when looking up the IP:port in our proxy mapper; it
// tracks which local IP:ports correspond to connections proxied by tailscaled,
// and since tailscaled proxies both TCP and UDP, the 'proto' is needed to look
// up the correct IP:port based on the connection's protocol. If not provided,
// the lookup will be done for TCP and then UDP, in that order.
//
// If ok == true, n and u are valid.
func (b *LocalBackend) WhoIs(proto string, ipp netip.AddrPort) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool) {
var zero tailcfg.NodeView
b.mu.Lock()
defer b.mu.Unlock()
failf := func(format string, args ...any) (tailcfg.NodeView, tailcfg.UserProfile, bool) {
if debugWhoIs() {
args = append([]any{proto, ipp}, args...)
b.logf("whois(%q, %v) :"+format, args...)
}
return zero, u, false
}
cn := b.currentNode()
nid, ok := cn.NodeByAddr(ipp.Addr())
if !ok && buildfeatures.HasNetstack {
var ip netip.Addr
if ipp.Port() != 0 {
var protos []string
if proto != "" {
protos = []string{proto}
} else {
// If the user didn't specify a protocol, try all of them
protos = []string{"tcp", "udp"}
}
for _, tryproto := range protos {
ip, ok = b.sys.ProxyMapper().WhoIsIPPort(tryproto, ipp)
if ok {
break
}
}
}
if !ok {
return failf("no IP found in ProxyMapper for %v", ipp)
}
nid, ok = cn.NodeByAddr(ip)
if !ok {
return failf("no node for proxymapped IP %v", ip)
}
}
nm := cn.NetMap()
if nm == nil {
return failf("no netmap")
}
n, ok = cn.NodeByID(nid)
if !ok {
return zero, u, false
}
up, ok := cn.UserByID(n.User())
if !ok {
return failf("no userprofile for node %v", n.Key())
}
return n, profileFromView(up), true
}
// PeerCaps returns the capabilities that remote src IP has to
// ths current node.
func (b *LocalBackend) PeerCaps(src netip.Addr) tailcfg.PeerCapMap {
return b.currentNode().PeerCaps(src)
}
func (b *LocalBackend) GetFilterForTest() *filter.Filter {
testenv.AssertInTest()
nb := b.currentNode()
return nb.filterAtomic.Load()
}
// SetControlClientStatus is the callback invoked by the control client whenever it posts a new status.
// Among other things, this is where we update the netmap, packet filters, DNS and DERP maps.
func (b *LocalBackend) SetControlClientStatus(c controlclient.Client, st controlclient.Status) {
if b.ignoreControlClientUpdates.Load() {
b.logf("ignoring SetControlClientStatus during controlclient shutdown")
return
}
b.mu.Lock()
defer b.mu.Unlock()
b.setControlClientStatusLocked(c, st)
}
// setControlClientStatusLocked is the locked version of SetControlClientStatus.
//
// b.mu must be held.
func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st controlclient.Status) {
if b.cc != c {
b.logf("Ignoring SetControlClientStatus from old client")
return
}
if st.Err != nil {
if errors.Is(st.Err, io.EOF) {
b.logf("[v1] Received error: EOF")
return
}
b.logf("Received error: %v", st.Err)
if vizerr, ok := vizerror.As(st.Err); ok {
s := vizerr.Error()
b.sendLocked(ipn.Notify{ErrMessage: &s})
}
return
}
// Track the number of calls
currCall := b.numClientStatusCalls.Add(1)
// Handle node expiry in the netmap
if st.NetMap != nil {
now := b.clock.Now()
b.em.flagExpiredPeers(st.NetMap, now)
// Always stop the existing netmap timer if we have a netmap;
// it's possible that we have no nodes expiring, so we should
// always cancel the timer and then possibly restart it below.
if b.nmExpiryTimer != nil {
// Ignore if we can't stop; the atomic check in the
// AfterFunc (below) will skip running.
b.nmExpiryTimer.Stop()
// Nil so we don't attempt to stop on the next netmap
b.nmExpiryTimer = nil
}
// Figure out when the next node in the netmap is expiring so we can
// start a timer to reconfigure at that point.
nextExpiry := b.em.nextPeerExpiry(st.NetMap, now)
if !nextExpiry.IsZero() {
tmrDuration := nextExpiry.Sub(now) + 10*time.Second
b.nmExpiryTimer = b.clock.AfterFunc(tmrDuration, func() {
// Skip if the world has moved on past the
// saved call (e.g. if we race stopping this
// timer).
if b.numClientStatusCalls.Load() != currCall {
return
}
b.logf("setClientStatus: netmap expiry timer triggered after %v", tmrDuration)
// Call ourselves with the current status again; the logic in
// setClientStatus will take care of updating the expired field
// of peers in the netmap.
b.SetControlClientStatus(c, st)
})
}
}
wasBlocked := b.blocked
authWasInProgress := b.authURL != ""
keyExpiryExtended := false
if st.NetMap != nil {
wasExpired := b.keyExpired
isExpired := !st.NetMap.SelfKeyExpiry().IsZero() && st.NetMap.SelfKeyExpiry().Before(b.clock.Now())
if wasExpired && !isExpired {
keyExpiryExtended = true
}
b.keyExpired = isExpired
}
if keyExpiryExtended && wasBlocked {
// Key extended, unblock the engine
b.blockEngineUpdatesLocked(false)
}
if st.LoggedIn && (wasBlocked || authWasInProgress) {
if wasBlocked {
// Auth completed, unblock the engine
b.blockEngineUpdatesLocked(false)
}
b.authReconfigLocked()
b.sendLocked(ipn.Notify{LoginFinished: &empty.Message{}})
}
prefsChanged := false
cn := b.currentNode()
prefs := b.pm.CurrentPrefs().AsStruct()
oldNetMap := cn.NetMap()
curNetMap := st.NetMap
if curNetMap == nil {
// The status didn't include a netmap update, so the old one is still
// current.
curNetMap = oldNetMap
}
if prefs.ControlURL == "" {
// Once we get a message from the control plane, set
// our ControlURL pref explicitly. This causes a
// future "tailscale up" to start checking for
// implicit setting reverts, which it doesn't do when
// ControlURL is blank.
prefs.ControlURL = prefs.ControlURLOrDefault(b.polc)
prefsChanged = true
}
if st.Persist.Valid() {
if !prefs.Persist.View().Equals(st.Persist) {
prefsChanged = true
prefs.Persist = st.Persist.AsStruct()
}
}
if st.LoggedIn {
if authWasInProgress {
b.resetAuthURLLocked()
// Interactive login finished successfully (URL visited).
// After an interactive login, the user always wants
// WantRunning.
if !prefs.WantRunning {
prefs.WantRunning = true
prefsChanged = true
}
}
if prefs.LoggedOut {
prefs.LoggedOut = false
prefsChanged = true
}
}
// We primarily need this to apply syspolicy to the prefs if an implicit profile
// switch is about to happen.
// TODO(nickkhyl): remove this once we improve handling of implicit profile switching
// in tailscale/corp#28014 and we apply syspolicy when the switch actually happens.
if b.reconcilePrefsLocked(prefs) {
prefsChanged = true
}
// Until recently, we did not store the account's tailnet name. So check if this is the case,
// and backfill it on incoming status update.
if b.pm.requiresBackfill() && st.NetMap != nil && st.NetMap.Domain != "" {
prefsChanged = true
}
// If the tailnet's display name has changed, update prefs.
if st.NetMap != nil && st.NetMap.TailnetDisplayName() != b.pm.CurrentProfile().NetworkProfile().DisplayName {
prefsChanged = true
}
// Perform all mutations of prefs based on the netmap here.
if prefsChanged {
// Prefs will be written out if stale; this is not safe unless locked or cloned.
if err := b.pm.SetPrefs(prefs.View(), ipn.NetworkProfile{
MagicDNSName: curNetMap.MagicDNSSuffix(),
DomainName: curNetMap.DomainName(),
DisplayName: curNetMap.TailnetDisplayName(),
}); err != nil {
b.logf("Failed to save new controlclient state: %v", err)
}
b.sendToLocked(ipn.Notify{Prefs: new(prefs.View())}, allClients)
}
// initTKALocked is dependent on CurrentProfile.ID, which is initialized
// (for new profiles) on the first call to b.pm.SetPrefs.
if err := b.initTKALocked(); err != nil {
b.logf("initTKALocked: %v", err)
}
// Perform all reconfiguration based on the netmap here.
if st.NetMap != nil {
b.capTailnetLock = st.NetMap.HasCap(tailcfg.CapabilityTailnetLock)
b.setWebClientAtomicBoolLocked(st.NetMap)
b.mu.Unlock() // respect locking rules for tkaSyncIfNeeded
if err := b.tkaSyncIfNeeded(st.NetMap, prefs.View()); err != nil {
b.logf("[v1] TKA sync error: %v", err)
}
b.mu.Lock()
// As we stepped outside of the lock, it's possible for b.cc
// to now be nil.
if b.cc != nil {
if b.tka != nil {
head, err := b.tka.authority.Head().MarshalText()
if err != nil {
b.logf("[v1] error marshalling tka head: %v", err)
} else {
b.cc.SetTKAHead(string(head))
}
} else {
b.cc.SetTKAHead("")
}
}
if !envknob.TKASkipSignatureCheck() {
b.tkaFilterNetmapLocked(st.NetMap)
}
b.setNetMapLocked(st.NetMap)
b.updateFilterLocked(prefs.View())
}
// Now complete the lock-free parts of what we started while locked.
if st.NetMap != nil {
if envknob.NoLogsNoSupport() && st.NetMap.HasCap(tailcfg.CapabilityDataPlaneAuditLogs) {
msg := "tailnet requires logging to be enabled. Remove --no-logs-no-support from tailscaled command line."
b.health.SetLocalLogConfigHealth(errors.New(msg))
// Get the current prefs again, since we unlocked above.
prefs := b.pm.CurrentPrefs().AsStruct()
prefs.WantRunning = false
p := prefs.View()
if err := b.pm.SetPrefs(p, ipn.NetworkProfile{
MagicDNSName: st.NetMap.MagicDNSSuffix(),
DomainName: st.NetMap.DomainName(),
DisplayName: st.NetMap.TailnetDisplayName(),
}); err != nil {
b.logf("Failed to save new controlclient state: %v", err)
}
b.sendLocked(ipn.Notify{ErrMessage: &msg, Prefs: &p})
return
}
if oldNetMap != nil {
diff := st.NetMap.ConciseDiffFrom(oldNetMap)
if strings.TrimSpace(diff) == "" {
b.logf("[v1] netmap diff: (none)")
} else {
b.logf("[v1] netmap diff:\n%v", diff)
}
}
b.e.SetNetworkMap(st.NetMap)
b.MagicConn().SetDERPMap(st.NetMap.DERPMap)
b.MagicConn().SetOnlyTCP443(st.NetMap.HasCap(tailcfg.NodeAttrOnlyTCP443))
// Update our cached DERP map
dnsfallback.UpdateCache(st.NetMap.DERPMap, b.logf)
// Update the DERP map in the health package, which uses it for health notifications
b.health.SetDERPMap(st.NetMap.DERPMap)
b.sendLocked(ipn.Notify{NetMap: st.NetMap})
// The error here is unimportant as is the result. This will recalculate the suggested exit node
// cache the value and push any changes to the IPN bus.
b.suggestExitNodeLocked()
// Check and update the exit node if needed, now that we have a new netmap.
//
// This must happen after the netmap change is sent via [ipn.Notify],
// so the GUI can correctly display the exit node if it has changed
// since the last netmap was sent.
//
// Otherwise, it might briefly show the exit node as offline and display a warning,
// if the node wasn't online or wasn't advertising default routes in the previous netmap.
b.refreshExitNodeLocked()
}
if st.URL != "" {
b.logf("Received auth URL: %.20v...", st.URL)
b.setAuthURLLocked(st.URL)
}
b.stateMachineLocked()
// This is currently (2020-07-28) necessary; conditionally disabling it is fragile!
// This is where netmap information gets propagated to router and magicsock.
b.authReconfigLocked()
}
func (b *LocalBackend) PatchDiscoKey(pub key.NodePublic, disco key.DiscoPublic) {
// PatchDiscoKey mirrors the implementation of [controlclient.patchDiscoKeyer].
// It is implemented here to avoid the dependency edge to controlclient, but must be kept
// in sync with the original implementation.
type patchDiscoKeyer interface {
PatchDiscoKey(key.NodePublic, key.DiscoPublic)
}
if e, ok := b.e.(patchDiscoKeyer); ok {
e.PatchDiscoKey(pub, disco)
}
}
type preferencePolicyInfo struct {
key pkey.Key
get func(ipn.PrefsView) bool
set func(*ipn.Prefs, bool)
}
var preferencePolicies = []preferencePolicyInfo{
{
key: pkey.EnableIncomingConnections,
// Allow Incoming (used by the UI) is the negation of ShieldsUp (used by the
// backend), so this has to convert between the two conventions.
get: func(p ipn.PrefsView) bool { return !p.ShieldsUp() },
set: func(p *ipn.Prefs, v bool) { p.ShieldsUp = !v },
},
{
key: pkey.EnableServerMode,
get: func(p ipn.PrefsView) bool { return p.ForceDaemon() },
set: func(p *ipn.Prefs, v bool) { p.ForceDaemon = v },
},
{
key: pkey.ExitNodeAllowLANAccess,
get: func(p ipn.PrefsView) bool { return p.ExitNodeAllowLANAccess() },
set: func(p *ipn.Prefs, v bool) { p.ExitNodeAllowLANAccess = v },
},
{
key: pkey.EnableTailscaleDNS,
get: func(p ipn.PrefsView) bool { return p.CorpDNS() },
set: func(p *ipn.Prefs, v bool) { p.CorpDNS = v },
},
{
key: pkey.EnableTailscaleSubnets,
get: func(p ipn.PrefsView) bool { return p.RouteAll() },
set: func(p *ipn.Prefs, v bool) { p.RouteAll = v },
},
{
key: pkey.CheckUpdates,
get: func(p ipn.PrefsView) bool { return p.AutoUpdate().Check },
set: func(p *ipn.Prefs, v bool) { p.AutoUpdate.Check = v },
},
{
key: pkey.ApplyUpdates,
get: func(p ipn.PrefsView) bool { v, _ := p.AutoUpdate().Apply.Get(); return v },
set: func(p *ipn.Prefs, v bool) { p.AutoUpdate.Apply.Set(v) },
},
{
key: pkey.EnableRunExitNode,
get: func(p ipn.PrefsView) bool { return p.AdvertisesExitNode() },
set: func(p *ipn.Prefs, v bool) { p.SetAdvertiseExitNode(v) },
},
}
// applySysPolicyLocked overwrites configured preferences with policies that may be
// configured by the system administrator in an OS-specific way.
//
// b.mu must be held.
func (b *LocalBackend) applySysPolicyLocked(prefs *ipn.Prefs) (anyChange bool) {
if !buildfeatures.HasSystemPolicy {
return false
}
syncs.RequiresMutex(&b.mu)
if controlURL, err := b.polc.GetString(pkey.ControlURL, prefs.ControlURL); err == nil && prefs.ControlURL != controlURL {
prefs.ControlURL = controlURL
anyChange = true
}
const sentinel = "HostnameDefaultValue"
hostnameFromPolicy, _ := b.polc.GetString(pkey.Hostname, sentinel)
switch hostnameFromPolicy {
case sentinel:
// An empty string for this policy value means that the admin wants to delete
// the hostname stored in the ipn.Prefs. To make that work, we need to
// distinguish between an empty string and a policy that was not set.
// We cannot do that with the current implementation of syspolicy.GetString.
// It currently does not return an error if a policy was not configured.
// Instead, it returns the default value provided as the second argument.
// This behavior makes it impossible to distinguish between a policy that
// was not set and a policy that was set to an empty default value.
// Checking for sentinel here is a workaround to distinguish between
// the two cases. If we get it, we do nothing because the policy was not set.
//
// TODO(angott,nickkhyl): clean up this behavior once syspolicy.GetString starts
// properly returning errors.
case "":
// The policy was set to an empty string, which means the admin intends
// to clear the hostname stored in preferences.
prefs.Hostname = ""
anyChange = true
default:
// The policy was set to a non-empty string, which means the admin wants
// to override the hostname stored in preferences.
if prefs.Hostname != hostnameFromPolicy {
prefs.Hostname = hostnameFromPolicy
anyChange = true
}
}
// Only apply the exit node policy if the user hasn't overridden it.
if !b.overrideExitNodePolicy && b.applyExitNodeSysPolicyLocked(prefs) {
anyChange = true
}
if alwaysOn, _ := b.polc.GetBoolean(pkey.AlwaysOn, false); alwaysOn && !b.overrideAlwaysOn && !prefs.WantRunning {
prefs.WantRunning = true
anyChange = true
}
for _, opt := range preferencePolicies {
if po, err := b.polc.GetPreferenceOption(opt.key, ptype.ShowChoiceByPolicy); err == nil {
curVal := opt.get(prefs.View())
newVal := po.ShouldEnable(curVal)
if curVal != newVal {
opt.set(prefs, newVal)
anyChange = true
}
}
}
return anyChange
}
// applyExitNodeSysPolicyLocked applies the exit node policy settings to prefs
// and reports whether any change was made.
//
// b.mu must be held.
func (b *LocalBackend) applyExitNodeSysPolicyLocked(prefs *ipn.Prefs) (anyChange bool) {
if !buildfeatures.HasUseExitNode {
return false
}
syncs.RequiresMutex(&b.mu)
if exitNodeIDStr, _ := b.polc.GetString(pkey.ExitNodeID, ""); exitNodeIDStr != "" {
exitNodeID := tailcfg.StableNodeID(exitNodeIDStr)
// Try to parse the policy setting value as an "auto:"-prefixed [ipn.ExitNodeExpression],
// and update prefs if it differs from the current one.
// This includes cases where it was previously an expression but no longer is,
// or where it wasn't before but now is.
autoExitNode, useAutoExitNode := ipn.ParseAutoExitNodeString(exitNodeID)
if prefs.AutoExitNode != autoExitNode {
prefs.AutoExitNode = autoExitNode
anyChange = true
}
// Additionally, if the specified exit node ID is an expression,
// meaning an exit node is required but we don't yet have a valid exit node ID,
// we should set exitNodeID to a value that is never a valid [tailcfg.StableNodeID],
// to install a blackhole route and prevent accidental non-exit-node usage
// until the expression is evaluated and an actual exit node is selected.
// We use "auto:any" for this purpose, primarily for compatibility with
// older clients (in case a user downgrades to an earlier version)
// and GUIs/CLIs that have special handling for it.
if useAutoExitNode {
exitNodeID = unresolvedExitNodeID
}
// If the current exit node ID doesn't match the one enforced by the policy setting,
// and the policy either requires a specific exit node ID,
// or requires an auto exit node ID and the current one isn't allowed,
// then update the exit node ID.
if prefs.ExitNodeID != exitNodeID {
if !useAutoExitNode || !isAllowedAutoExitNodeID(b.polc, prefs.ExitNodeID) {
prefs.ExitNodeID = exitNodeID
anyChange = true
}
}
// If the exit node IP is set, clear it. When ExitNodeIP is set in the prefs,
// it takes precedence over the ExitNodeID.
if prefs.ExitNodeIP.IsValid() {
prefs.ExitNodeIP = netip.Addr{}
anyChange = true
}
} else if exitNodeIPStr, _ := b.polc.GetString(pkey.ExitNodeIP, ""); exitNodeIPStr != "" {
if prefs.AutoExitNode != "" {
prefs.AutoExitNode = "" // mutually exclusive with ExitNodeIP
anyChange = true
}
if exitNodeIP, err := netip.ParseAddr(exitNodeIPStr); err == nil {
if prefs.ExitNodeID != "" || prefs.ExitNodeIP != exitNodeIP {
anyChange = true
}
prefs.ExitNodeID = ""
prefs.ExitNodeIP = exitNodeIP
}
}
return anyChange
}
// registerSysPolicyWatch subscribes to syspolicy change notifications
// and immediately applies the effective syspolicy settings to the current profile.
func (b *LocalBackend) registerSysPolicyWatch() (unregister func(), err error) {
if unregister, err = b.polc.RegisterChangeCallback(b.sysPolicyChanged); err != nil {
return nil, fmt.Errorf("syspolicy: LocalBacked failed to register policy change callback: %v", err)
}
if prefs, anyChange := b.reconcilePrefs(); anyChange {
b.logf("syspolicy: changed initial profile prefs: %v", prefs.Pretty())
}
b.refreshAllowedSuggestions()
return unregister, nil
}
// reconcilePrefs overwrites the current profile's preferences with policies
// that may be configured by the system administrator in an OS-specific way.
//
// b.mu must not be held.
func (b *LocalBackend) reconcilePrefs() (_ ipn.PrefsView, anyChange bool) {
b.mu.Lock()
defer b.mu.Unlock()
prefs := b.pm.CurrentPrefs().AsStruct()
if !b.reconcilePrefsLocked(prefs) {
return prefs.View(), false
}
return b.setPrefsLocked(prefs), true
}
// sysPolicyChanged is a callback triggered by syspolicy when it detects
// a change in one or more syspolicy settings.
func (b *LocalBackend) sysPolicyChanged(policy policyclient.PolicyChange) {
if policy.HasChangedAnyOf(pkey.AlwaysOn, pkey.AlwaysOnOverrideWithReason) {
// If the AlwaysOn or the AlwaysOnOverrideWithReason policy has changed,
// we should reset the overrideAlwaysOn flag, as the override might
// no longer be valid.
b.mu.Lock()
b.overrideAlwaysOn = false
b.mu.Unlock()
}
if policy.HasChangedAnyOf(pkey.ExitNodeID, pkey.ExitNodeIP, pkey.AllowExitNodeOverride) {
// Reset the exit node override if a policy that enforces exit node usage
// or allows the user to override automatic exit node selection has changed.
b.mu.Lock()
b.overrideExitNodePolicy = false
b.mu.Unlock()
}
if buildfeatures.HasUseExitNode && policy.HasChanged(pkey.AllowedSuggestedExitNodes) {
b.refreshAllowedSuggestions()
// Re-evaluate exit node suggestion now that the policy setting has changed.
if _, err := b.SuggestExitNode(); err != nil && !errors.Is(err, ErrNoPreferredDERP) {
b.logf("failed to select auto exit node: %v", err)
}
// If [pkey.ExitNodeID] is set to `auto:any`, the suggested exit node ID
// will be used when [applySysPolicy] updates the current profile's prefs.
}
if prefs, anyChange := b.reconcilePrefs(); anyChange {
b.logf("syspolicy: changed profile prefs: %v", prefs.Pretty())
}
}
var _ controlclient.NetmapDeltaUpdater = (*LocalBackend)(nil)
// UpdateNetmapDelta implements controlclient.NetmapDeltaUpdater.
func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bool) {
var notify *ipn.Notify // non-nil if we need to send a Notify
defer func() {
if notify != nil {
b.send(*notify)
}
}()
b.mu.Lock()
defer b.mu.Unlock()
cn := b.currentNode()
cn.UpdateNetmapDelta(muts)
if ms, ok := b.sys.MagicSock.GetOK(); ok {
ms.UpdateNetmapDelta(muts)
}
// If auto exit nodes are enabled and our exit node went offline,
// we need to schedule picking a new one.
// TODO(nickkhyl): move the auto exit node logic to a feature package.
if prefs := b.pm.CurrentPrefs(); prefs.AutoExitNode().IsSet() {
exitNodeID := prefs.ExitNodeID()
for _, m := range muts {
mo, ok := m.(netmap.NodeMutationOnline)
if !ok || mo.Online {
continue
}
n, ok := cn.NodeByID(m.NodeIDBeingMutated())
if !ok || n.StableID() != exitNodeID {
continue
}
b.refreshExitNodeLocked()
break
}
}
if cn.NetMap() != nil && mutationsAreWorthyOfRecalculatingSuggestedExitNode(muts, cn, b.lastSuggestedExitNode) {
// Recompute the suggested exit node
b.suggestExitNodeLocked()
}
if cn.NetMap() == nil {
b.logf("[unexpected] got node mutations but netmap is nil; mutations not applied")
return true
}
if mutationsAreWorthyOfTellingIPNBus(muts) {
// The notifier will strip the netmap based on the watchOpts mask if the watcher
// has indicated it can handle PeerChanges.
notify = &ipn.Notify{NetMap: cn.netMapWithPeers()}
if peerChanges, ok := ipnBusPeerChangesFromNodeMutations(muts); ok {
notify.PeerChanges = peerChanges
} else {
b.logf("[unexpected] got mutations worthy of telling IPN bus but failed to convert to peer changes")
}
} else if testenv.InTest() {
// In tests, send an empty Notify as a wake-up so end-to-end
// integration tests in another repo can check on the status of
// LocalBackend after processing deltas.
notify = new(ipn.Notify)
}
return true
}
// mustationsAreWorthyOfRecalculatingSuggestedExitNode reports whether any mutation type in muts is
// worthy of recalculating the suggested exit node.
func mutationsAreWorthyOfRecalculatingSuggestedExitNode(muts []netmap.NodeMutation, cn *nodeBackend, sid tailcfg.StableNodeID) bool {
if !buildfeatures.HasUseExitNode {
return false
}
for _, m := range muts {
n, ok := cn.NodeByID(m.NodeIDBeingMutated())
if !ok {
// The node being mutated is not in the netmap.
continue
}
// The previously suggested exit node itself is being mutated.
if sid != "" && n.StableID() == sid {
return true
}
allowed := n.AllowedIPs().AsSlice()
isExitNode := slices.Contains(allowed, tsaddr.AllIPv4()) || slices.Contains(allowed, tsaddr.AllIPv6())
// The node being mutated is not an exit node. We don't care about it - unless
// it was our previously suggested exit node which we catch above.
if !isExitNode {
continue
}
// Some exit node is being mutated. We care about it if it's online
// or offline state has changed. We *might* eventually care about it for other reasons
// but for the sake of finding a "better" suggested exit node, this is probably
// sufficient.
switch m.(type) {
case netmap.NodeMutationOnline:
return true
}
}
return false
}
// ipnBusPeerChangesFromNodeMutations converts a slice of NodeMutations to a slice of
// *tailcfg.PeerChange for use in ipn.Notify.PeerChanges.
// Multiple mutations to the same node are merged into a single PeerChange.
// If we encounter any mutations that we cannot convert to a PeerChange, we return (nil, false)
// to indicate that the caller should send a Notify with the full netmap instead of
// trying to send granular peer changes.
func ipnBusPeerChangesFromNodeMutations(muts []netmap.NodeMutation) ([]*tailcfg.PeerChange, bool) {
byID := map[tailcfg.NodeID]*tailcfg.PeerChange{}
var ordered []*tailcfg.PeerChange
for _, m := range muts {
nid := m.NodeIDBeingMutated()
pc := byID[nid]
if pc == nil {
pc = &tailcfg.PeerChange{NodeID: nid}
byID[nid] = pc
ordered = append(ordered, pc)
}
switch v := m.(type) {
case netmap.NodeMutationOnline:
pc.Online = &v.Online
case netmap.NodeMutationLastSeen:
pc.LastSeen = &v.LastSeen
case netmap.NodeMutationDERPHome:
pc.DERPRegion = v.DERPRegion
case netmap.NodeMutationEndpoints:
pc.Endpoints = v.Endpoints
default:
return nil, false
}
}
return ordered, true
}
// mutationsAreWorthyOfTellingIPNBus reports whether any mutation type in muts is
// worthy of spamming the IPN bus (the Windows & Mac GUIs, basically) to tell them
// about the update.
func mutationsAreWorthyOfTellingIPNBus(muts []netmap.NodeMutation) bool {
for _, m := range muts {
switch m.(type) {
case netmap.NodeMutationLastSeen,
netmap.NodeMutationOnline:
// The GUI clients might render peers differently depending on whether
// they're online.
return true
}
}
return false
}
// resolveAutoExitNodeLocked computes a suggested exit node and updates prefs
// to use it if AutoExitNode is enabled, and reports whether prefs was mutated.
//
// b.mu must be held.
func (b *LocalBackend) resolveAutoExitNodeLocked(prefs *ipn.Prefs) (prefsChanged bool) {
if !buildfeatures.HasUseExitNode {
return false
}
syncs.RequiresMutex(&b.mu)
// As of 2025-07-08, the only supported auto exit node expression is [ipn.AnyExitNode].
//
// However, to maintain forward compatibility with future auto exit node expressions,
// we treat any non-empty AutoExitNode as [ipn.AnyExitNode].
//
// If and when we support additional auto exit node expressions, this method should be updated
// to handle them appropriately, while still falling back to [ipn.AnyExitNode] or a more appropriate
// default for unknown (or partially supported) expressions.
if !prefs.AutoExitNode.IsSet() {
return false
}
if _, err := b.suggestExitNodeLocked(); err != nil && !errors.Is(err, ErrNoPreferredDERP) {
b.logf("failed to select auto exit node: %v", err) // non-fatal, see below
}
var newExitNodeID tailcfg.StableNodeID
if !b.lastSuggestedExitNode.IsZero() {
// If we have a suggested exit node, use it.
newExitNodeID = b.lastSuggestedExitNode
} else if isAllowedAutoExitNodeID(b.polc, prefs.ExitNodeID) {
// If we don't have a suggested exit node, but the prefs already
// specify an allowed auto exit node ID, retain it.
newExitNodeID = prefs.ExitNodeID
} else {
// Otherwise, use [unresolvedExitNodeID] to install a blackhole route,
// preventing traffic from leaking to the local network until an actual
// exit node is selected.
newExitNodeID = unresolvedExitNodeID
}
if prefs.ExitNodeID != newExitNodeID {
prefs.ExitNodeID = newExitNodeID
prefsChanged = true
}
if prefs.ExitNodeIP.IsValid() {
prefs.ExitNodeIP = netip.Addr{}
prefsChanged = true
}
return prefsChanged
}
// resolveExitNodeIPLocked updates prefs to reference an exit node by ID, rather
// than by IP. It returns whether prefs was mutated.
//
// b.mu must be held.
func (b *LocalBackend) resolveExitNodeIPLocked(prefs *ipn.Prefs) (prefsChanged bool) {
if !buildfeatures.HasUseExitNode {
return false
}
// If we have a desired IP on file, try to find the corresponding node.
if !prefs.ExitNodeIP.IsValid() {
return false
}
// IP takes precedence over ID, so if both are set, clear ID.
if prefs.ExitNodeID != "" {
prefs.ExitNodeID = ""
prefsChanged = true
}
cn := b.currentNode()
if nid, ok := cn.NodeByAddr(prefs.ExitNodeIP); ok {
if node, ok := cn.NodeByID(nid); ok {
// Found the node being referenced, upgrade prefs to
// reference it directly for next time.
prefs.ExitNodeID = node.StableID()
prefs.ExitNodeIP = netip.Addr{}
// Cleared ExitNodeIP, so prefs changed
// even if the ID stayed the same.
prefsChanged = true
}
}
return prefsChanged
}
// setWgengineStatus is the callback by the wireguard engine whenever it posts a new status.
// This updates the endpoints both in the backend and in the control client.
func (b *LocalBackend) setWgengineStatus(s *wgengine.Status, err error) {
if err != nil {
b.logf("wgengine status error: %v", err)
return
}
if s == nil {
b.logf("[unexpected] non-error wgengine update with status=nil: %v", s)
return
}
b.mu.Lock()
defer b.mu.Unlock()
// For now, only check this in the callback, but don't check it in setWgengineStatusLocked
if s.AsOf.Before(b.lastStatusTime) {
// Don't process a status update that is older than the one we have
// already processed. (corp#2579)
return
}
b.lastStatusTime = s.AsOf
b.setWgengineStatusLocked(s)
}
// setWgengineStatusLocked updates LocalBackend's view of the engine status and
// updates the endpoints both in the backend and in the control client.
//
// Unlike setWgengineStatus it does not discard out-of-order updates, so
// statuses sent here are always processed. This is useful for ensuring we don't
// miss a "we shut down" status during backend shutdown even if other statuses
// arrive out of order.
//
// TODO(zofrex): we should ensure updates actually do arrive in order and move
// the out-of-order check into this function.
//
// b.mu must be held.
func (b *LocalBackend) setWgengineStatusLocked(s *wgengine.Status) {
syncs.RequiresMutex(&b.mu)
es := b.parseWgStatusLocked(s)
cc := b.cc
// TODO(zofrex): the only reason we even write this is to transition from
// "Starting" to "Running" in the call to state machine a few lines below
// this. Maybe we don't even need to store it at all.
b.engineStatus = es
needUpdateEndpoints := !slices.Equal(s.LocalAddrs, b.endpoints)
if needUpdateEndpoints {
b.endpoints = append([]tailcfg.Endpoint{}, s.LocalAddrs...)
}
if cc != nil {
if needUpdateEndpoints {
cc.UpdateEndpoints(s.LocalAddrs)
}
b.stateMachineLocked()
}
b.sendLocked(ipn.Notify{Engine: &es})
}
// SetNotifyCallback sets the function to call when the backend has something to
// notify the frontend about. Only one callback can be set at a time, so calling
// this function will replace the previous callback.
func (b *LocalBackend) SetNotifyCallback(notify func(ipn.Notify)) {
ctx, cancel := context.WithCancel(b.ctx)
b.mu.Lock()
prevCancel := b.notifyCancel
b.notifyCancel = cancel
b.mu.Unlock()
if prevCancel != nil {
prevCancel()
}
var wg sync.WaitGroup
wg.Add(1)
go b.WatchNotifications(ctx, 0, wg.Done, func(n *ipn.Notify) bool {
notify(*n)
return true
})
wg.Wait()
}
// SetHTTPTestClient sets an alternate HTTP client to use with
// connections to the coordination server. It exists for
// testing. Using nil means to use the default.
func (b *LocalBackend) SetHTTPTestClient(c *http.Client) {
b.mu.Lock()
defer b.mu.Unlock()
b.httpTestClient = c
}
// SetControlClientGetterForTesting sets the func that creates a
// control plane client. It can be called at most once, before Start.
func (b *LocalBackend) SetControlClientGetterForTesting(newControlClient func(controlclient.Options) (controlclient.Client, error)) {
b.mu.Lock()
defer b.mu.Unlock()
if b.ccGen != nil {
panic("invalid use of SetControlClientGetterForTesting after Start")
}
b.ccGen = newControlClient
}
// PeersForTest returns all the current peers, sorted by Node.ID,
// for integration tests in another repo.
func (b *LocalBackend) PeersForTest() []tailcfg.NodeView {
testenv.AssertInTest()
return b.currentNode().PeersForTest()
}
func (b *LocalBackend) getNewControlClientFuncLocked() clientGen {
if b.ccGen == nil {
// Initialize it rather than just returning the
// default to make any future call to
// SetControlClientGetterForTesting panic.
b.ccGen = func(opts controlclient.Options) (controlclient.Client, error) {
return controlclient.New(opts)
}
}
return b.ccGen
}
// initOnce is called on the first call to [LocalBackend.Start].
func (b *LocalBackend) initOnce() {
b.extHost.Init()
}
func (b *LocalBackend) controlDebugFlags() []string {
debugFlags := controlDebugFlags
if b.sys.IsNetstackRouter() {
return append([]string{"netstack"}, debugFlags...)
}
return debugFlags
}
// Start applies the configuration specified in opts, and starts the
// state machine.
//
// TODO(danderson): this function is trying to do too many things at
// once: it loads state, or imports it, or updates prefs sometimes,
// contains some settings that are one-shot things done by `tailscale
// up` because we had nowhere else to put them, and there's no clear
// guarantee that switching from one user's state to another is
// actually a supported operation (it should be, but it's very unclear
// from the following whether or not that is a safe transition).
func (b *LocalBackend) Start(opts ipn.Options) error {
b.mu.Lock()
defer b.mu.Unlock()
return b.startLocked(opts)
}
func (b *LocalBackend) startLocked(opts ipn.Options) error {
b.logf("Start")
logf := logger.WithPrefix(b.logf, "Start: ")
b.startOnce.Do(b.initOnce)
var clientToShutdown controlclient.Client
defer func() {
if clientToShutdown != nil {
// Shutdown outside of b.mu to avoid deadlocks.
b.goTracker.Go(clientToShutdown.Shutdown)
}
}()
if opts.UpdatePrefs != nil {
if err := b.checkPrefsLocked(opts.UpdatePrefs); err != nil {
return err
}
}
if b.state != ipn.Running && b.conf != nil && b.conf.Parsed.AuthKey != nil && opts.AuthKey == "" {
v := *b.conf.Parsed.AuthKey
if filename, ok := strings.CutPrefix(v, "file:"); ok {
b, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("error reading config file authKey: %w", err)
}
v = strings.TrimSpace(string(b))
}
opts.AuthKey = v
}
if b.state != ipn.Running && b.conf == nil && opts.AuthKey == "" {
sysak, _ := b.polc.GetString(pkey.AuthKey, "")
if sysak != "" && len(b.pm.Profiles()) > 0 && b.state != ipn.NeedsLogin {
logf("not setting opts.AuthKey from syspolicy; login profiles exist, state=%v", b.state)
} else if sysak != "" {
logf("setting opts.AuthKey by syspolicy, len=%v", len(sysak))
opts.AuthKey = strings.TrimSpace(sysak)
}
}
hostinfo := hostinfo.New()
applyConfigToHostinfo(hostinfo, b.conf)
hostinfo.BackendLogID = b.backendLogID.String()
hostinfo.FrontendLogID = opts.FrontendLogID
hostinfo.Userspace.Set(b.sys.IsNetstack())
hostinfo.UserspaceRouter.Set(b.sys.IsNetstackRouter())
hostinfo.AppConnector.Set(b.appConnector != nil)
hostinfo.StateEncrypted = b.stateEncrypted()
b.logf.JSON(1, "Hostinfo", hostinfo)
// TODO(apenwarr): avoid the need to reinit controlclient.
// This will trigger a full relogin/reconfigure cycle every
// time a Handle reconnects to the backend. Ideally, we
// would send the new Prefs and everything would get back
// into sync with the minimal changes. But that's not how it
// is right now, which is a sign that the code is still too
// complicated.
clientToShutdown = b.resetControlClientLocked()
httpTestClient := b.httpTestClient
if b.hostinfo != nil {
hostinfo.Services = b.hostinfo.Services // keep any previous services
}
b.hostinfo = hostinfo
b.setStateLocked(ipn.NoState)
cn := b.currentNode()
var prefsChanged bool
var prefsChangedWhy []string
newPrefs := b.pm.CurrentPrefs().AsStruct()
if opts.UpdatePrefs != nil {
newPrefs = opts.UpdatePrefs.Clone()
prefsChanged = true
prefsChangedWhy = append(prefsChangedWhy, "opts.UpdatePrefs")
}
// Apply any syspolicy overrides, resolve exit node ID, etc.
// As of 2025-07-03, this is primarily needed in two cases:
// - when opts.UpdatePrefs is not nil
// - when Always Mode is enabled and we need to set WantRunning to true
if b.reconcilePrefsLocked(newPrefs) {
prefsChanged = true
prefsChangedWhy = append(prefsChangedWhy, "reconcilePrefsLocked")
}
// neither UpdatePrefs or reconciliation should change Persist
newPrefs.Persist = b.pm.CurrentPrefs().Persist().AsStruct()
if buildfeatures.HasTPM && b.HardwareAttested() {
if genKey, ok := feature.HookGenerateAttestationKeyIfEmpty.GetOk(); ok {
newKey, err := genKey(newPrefs.Persist, logf)
if err != nil {
logf("failed to populate attestation key from TPM: %v", err)
}
if newKey {
prefsChanged = true
prefsChangedWhy = append(prefsChangedWhy, "newKey")
}
}
}
// Remove any existing attestation key if HardwareAttested is false.
if !b.HardwareAttested() && newPrefs.Persist != nil && newPrefs.Persist.AttestationKey != nil && !newPrefs.Persist.AttestationKey.IsZero() {
newPrefs.Persist.AttestationKey = nil
prefsChanged = true
prefsChangedWhy = append(prefsChangedWhy, "removeAttestationKey")
}
if prefsChanged {
logf("updated prefs: %v, reason: %v", newPrefs.Pretty(), prefsChangedWhy)
if err := b.pm.SetPrefs(newPrefs.View(), cn.NetworkProfile()); err != nil {
logf("failed to save updated and reconciled prefs (but still using updated prefs in memory): %v", err)
}
}
prefs := newPrefs.View()
// Reset the always-on override whenever Start is called.
b.resetAlwaysOnOverrideLocked()
b.setAtomicValuesFromPrefsLocked(prefs)
b.updateNoSNATExitNodeWarning(prefs)
wantRunning := prefs.WantRunning()
if wantRunning {
if err := b.initMachineKeyLocked(); err != nil {
return fmt.Errorf("initMachineKeyLocked: %w", err)
}
}
loggedOut := prefs.LoggedOut()
serverURL := prefs.ControlURLOrDefault(b.polc)
if inServerMode := prefs.ForceDaemon(); inServerMode || runtime.GOOS == "windows" {
logf("serverMode=%v", inServerMode)
}
b.applyPrefsToHostinfoLocked(b.hostinfo, prefs)
b.updateWarnSync(prefs)
persistv := prefs.Persist().AsStruct()
if persistv == nil {
persistv = new(persist.Persist)
}
// At this point we do not yet know whether we are meant to cache netmaps by
// policy (as we have not yet spoken to the control plane).
//
// However, since we do not create or update a netmap cache unless we observe the
// [tailcfg.NodeAttrCachedNetworkMaps] capability, we can use the presence
// of the cached netmap as a signal that we were expected to do so as of the
// last time we updated the cache.
//
// If the policy has (since) changed, a subsequent network map from the control
// plane may remove the attribute, at which point we will drop the cache.
//
// As of 2026-03-25 we require the envknob set to read a cached netmap, with
// the envknob defaulted to true so we can use it as a safety override
// during rollout.
if envknob.BoolDefaultTrue("TS_USE_CACHED_NETMAP") {
if nm, ok := b.loadDiskCacheLocked(); ok {
logf("loaded netmap from disk cache; %d peers", len(nm.Peers))
b.setControlClientStatusLocked(nil, controlclient.Status{
NetMap: nm,
LoggedIn: true, // sure
})
}
}
discoPublic := b.MagicConn().DiscoPublicKey()
var ccShutdownCbs []func()
ccShutdown := func() {
for _, cb := range ccShutdownCbs {
cb()
}
}
var c2nHandler http.Handler
if buildfeatures.HasC2N {
c2nHandler = http.HandlerFunc(b.handleC2N)
}
// TODO(apenwarr): The only way to change the ServerURL is to
// re-run b.Start, because this is the only place we create a
// new controlclient. EditPrefs allows you to overwrite ServerURL,
// but it won't take effect until the next Start.
cc, err := b.getNewControlClientFuncLocked()(controlclient.Options{
GetMachinePrivateKey: b.createGetMachinePrivateKeyFunc(),
Logf: logger.WithPrefix(b.logf, "control: "),
Persist: *persistv,
ServerURL: serverURL,
AuthKey: opts.AuthKey,
Hostinfo: b.hostInfoWithServicesLocked(),
HTTPTestClient: httpTestClient,
DiscoPublicKey: discoPublic,
DebugFlags: b.controlDebugFlags(),
HealthTracker: b.health,
ExtraRootCAs: b.sys.ExtraRootCAs,
PolicyClient: b.sys.PolicyClientOrDefault(),
Pinger: b,
PopBrowserURL: b.tellClientToBrowseToURL,
Dialer: b.Dialer(),
Observer: b,
C2NHandler: c2nHandler,
DialPlan: &b.dialPlan, // pointer because it can't be copied
ControlKnobs: b.sys.ControlKnobs(),
Shutdown: ccShutdown,
Bus: b.sys.Bus.Get(),
StartPaused: prefs.Sync().EqualBool(false),
})
if err != nil {
return err
}
ccShutdownCbs = b.extHost.NotifyNewControlClient(cc, b.pm.CurrentProfile())
b.setControlClientLocked(cc)
endpoints := b.endpoints
if err := b.initTKALocked(); err != nil {
logf("initTKALocked: %v", err)
}
var tkaHead string
if b.tka != nil {
head, err := b.tka.authority.Head().MarshalText()
if err != nil {
return fmt.Errorf("marshalling tka head: %w", err)
}
tkaHead = string(head)
}
confWantRunning := b.conf != nil && wantRunning
if endpoints != nil {
cc.UpdateEndpoints(endpoints)
}
cc.SetTKAHead(tkaHead)
blid := b.backendLogID.String()
b.logf("Backend: logs: be:%v fe:%v", blid, opts.FrontendLogID)
b.sendToLocked(ipn.Notify{Prefs: &prefs}, allClients)
// initialize Taildrive shares from saved state
if fs, ok := b.sys.DriveForRemote.GetOK(); ok {
currentShares := b.pm.CurrentPrefs().DriveShares()
var shares []*drive.Share
for _, share := range currentShares.All() {
shares = append(shares, share.AsStruct())
}
fs.SetShares(shares)
}
if !loggedOut && (b.hasNodeKeyLocked() || confWantRunning) {
// If we know that we're either logged in or meant to be
// running, tell the controlclient that it should also assume
// that we need to be logged in.
//
// Without this, the state machine transitions to "NeedsLogin" implying
// that user interaction is required, which is not the case and can
// regress tsnet.Server restarts.
cc.Login(controlclient.LoginDefault)
}
b.stateMachineLocked()
return nil
}
// addServiceIPs adds the IP addresses of any VIP Services sent from the
// coordination server to the list of addresses that we expect to handle.
func addServiceIPs(localNetsB *netipx.IPSetBuilder, selfNode tailcfg.NodeView) error {
if !selfNode.Valid() {
return nil
}
serviceMap, err := tailcfg.UnmarshalNodeCapViewJSON[tailcfg.ServiceIPMappings](selfNode.CapMap(), tailcfg.NodeAttrServiceHost)
if err != nil {
return err
}
for _, sm := range serviceMap { // typically there will be exactly one of these
for _, serviceAddrs := range sm {
for _, addr := range serviceAddrs { // typically there will be exactly two of these
localNetsB.Add(addr)
}
}
}
return nil
}
// invalidPacketFilterWarnable is a Warnable to warn the user that the control server sent an invalid packet filter.
var invalidPacketFilterWarnable = health.Register(&health.Warnable{
Code: "invalid-packet-filter",
Title: "Invalid packet filter",
Severity: health.SeverityHigh,
Text: health.StaticMessage("The coordination server sent an invalid packet filter permitting traffic to unlocked nodes; rejecting all packets for safety"),
})
// filterInputs holds the inputs to the packet filter.
//
// Any field changes or additions here should be accompanied by a change to
// [filterInputs.Equal] and [filterInputs.Clone] if necessary. (e.g. non-view
// and non-value fields)
type filterInputs struct {
HaveNetmap bool
Addrs views.Slice[netip.Prefix]
FilterMatch views.Slice[filter.Match]
LocalNets views.Slice[netipx.IPRange]
LogNets views.Slice[netipx.IPRange]
ShieldsUp bool
SSHPolicy tailcfg.SSHPolicyView
}
func (fi *filterInputs) Equal(o *filterInputs) bool {
if fi == nil || o == nil {
return fi == o
}
return reflect.DeepEqual(fi, o)
}
func (fi *filterInputs) Clone() *filterInputs {
if fi == nil {
return nil
}
v := *fi // all fields are shallow copyable
return &v
}
// updateFilterLocked updates the packet filter in wgengine based on the
// given netMap and user preferences.
//
// b.mu must be held.
func (b *LocalBackend) updateFilterLocked(prefs ipn.PrefsView) {
// TODO(nickkhyl) split this into two functions:
// - (*nodeBackend).RebuildFilters() (normalFilter, jailedFilter *filter.Filter, changed bool),
// which would return packet filters for the current state and whether they changed since the last call.
// - (*LocalBackend).updateFilters(), which would use the above to update the engine with the new filters,
// notify b.sshServer, etc.
//
// For this, we would need to plumb a few more things into the [nodeBackend]. Most importantly,
// the current [ipn.PrefsView]), but also maybe also a b.logf and a b.health?
//
// NOTE(danderson): keep change detection as the first thing in
// this function. Don't try to optimize by returning early, more
// likely than not you'll just end up breaking the change
// detection and end up with the wrong filter installed. This is
// quite hard to debug, so save yourself the trouble.
var (
cn = b.currentNode()
netMap = cn.NetMap()
haveNetmap = netMap != nil
addrs views.Slice[netip.Prefix]
packetFilter []filter.Match
localNetsB netipx.IPSetBuilder
logNetsB netipx.IPSetBuilder
shieldsUp = !prefs.Valid() || prefs.ShieldsUp() // Be conservative when not ready
)
// Log traffic for Tailscale IPs.
logNetsB.AddPrefix(tsaddr.CGNATRange())
logNetsB.AddPrefix(tsaddr.TailscaleULARange())
logNetsB.RemovePrefix(tsaddr.ChromeOSVMRange())
if haveNetmap {
addrs = netMap.GetAddresses()
for i := range addrs.Len() {
localNetsB.AddPrefix(addrs.At(i))
}
packetFilter = netMap.PacketFilter
if cn.unlockedNodesPermitted(packetFilter) {
b.health.SetUnhealthy(invalidPacketFilterWarnable, nil)
packetFilter = nil
} else {
b.health.SetHealthy(invalidPacketFilterWarnable)
}
if err := addServiceIPs(&localNetsB, netMap.SelfNode); err != nil {
b.logf("addServiceIPs: %v", err)
}
}
if prefs.Valid() {
if buildfeatures.HasAdvertiseRoutes {
for _, r := range prefs.AdvertiseRoutes().All() {
if r.Bits() == 0 {
// When offering a default route to the world, we
// filter out locally reachable LANs, so that the
// default route effectively appears to be a "guest
// wifi": you get internet access, but to additionally
// get LAN access the LAN(s) need to be offered
// explicitly as well.
localInterfaceRoutes, hostIPs, err := interfaceRoutes()
if err != nil {
b.logf("getting local interface routes: %v", err)
continue
}
s, err := shrinkDefaultRoute(r, localInterfaceRoutes, hostIPs)
if err != nil {
b.logf("computing default route filter: %v", err)
continue
}
localNetsB.AddSet(s)
} else {
localNetsB.AddPrefix(r)
// When advertising a non-default route, we assume
// this is a corporate subnet that should be present
// in the audit logs.
logNetsB.AddPrefix(r)
}
}
}
// App connectors handle DNS requests for app domains over PeerAPI (corp#11961),
// but a safety check verifies the requesting peer has at least permission
// to send traffic to 0.0.0.0:53 (or 2000:: for IPv6) before handling the DNS
// request (see peerAPIHandler.replyToDNSQueries in peerapi.go).
// The correct filter rules are synthesized by the coordination server
// and sent down, but the address needs to be part of the 'local net' for the
// filter package to even bother checking the filter rules, so we set them here.
if buildfeatures.HasAppConnectors && prefs.AppConnector().Advertise {
localNetsB.Add(netip.MustParseAddr("0.0.0.0"))
localNetsB.Add(netip.MustParseAddr("::0"))
}
}
localNets, _ := localNetsB.IPSet()
logNets, _ := logNetsB.IPSet()
var sshPol tailcfg.SSHPolicyView
if buildfeatures.HasSSH && haveNetmap && netMap.SSHPolicy != nil {
sshPol = netMap.SSHPolicy.View()
}
changed := checkchange.Update(&b.lastFilterInputs, &filterInputs{
HaveNetmap: haveNetmap,
Addrs: addrs,
FilterMatch: views.SliceOf(packetFilter),
LocalNets: views.SliceOf(localNets.Ranges()),
LogNets: views.SliceOf(logNets.Ranges()),
ShieldsUp: shieldsUp,
SSHPolicy: sshPol,
})
if !changed {
return
}
if !haveNetmap {
b.logf("[v1] netmap packet filter: (not ready yet)")
noneFilter := filter.NewAllowNone(b.logf, logNets)
b.setFilter(noneFilter)
b.e.SetJailedFilter(noneFilter)
return
}
oldFilter := b.e.GetFilter()
if shieldsUp {
b.logf("[v1] netmap packet filter: (shields up)")
b.setFilter(filter.NewShieldsUpFilter(localNets, logNets, oldFilter, b.logf))
} else {
b.logf("[v1] netmap packet filter: %v filters", len(packetFilter))
filt := filter.New(packetFilter, b.srcIPHasCapForFilter, localNets, logNets, oldFilter, b.logf)
filt.IngressAllowHooks = b.extHost.Hooks().Filter.IngressAllowHooks
filt.LinkLocalAllowHooks = b.extHost.Hooks().Filter.LinkLocalAllowHooks
b.setFilter(filt)
}
// The filter for a jailed node is the exact same as a ShieldsUp filter.
oldJailedFilter := b.e.GetJailedFilter()
b.e.SetJailedFilter(filter.NewShieldsUpFilter(localNets, logNets, oldJailedFilter, b.logf))
if b.sshServer != nil {
b.goTracker.Go(b.sshServer.OnPolicyChange)
}
}
// packetFilterPermitsUnlockedNodes reports any peer in peers with the
// UnsignedPeerAPIOnly bool set true has any of its allowed IPs in the packet
// filter.
//
// If this reports true, the packet filter is invalid (the server is either broken
// or malicious) and should be ignored for safety.
func packetFilterPermitsUnlockedNodes(peers map[tailcfg.NodeID]tailcfg.NodeView, packetFilter []filter.Match) bool {
var b netipx.IPSetBuilder
var numUnlocked int
for _, p := range peers {
if !p.UnsignedPeerAPIOnly() {
continue
}
numUnlocked++
for _, pfx := range p.AllowedIPs().All() { // not only addresses!
b.AddPrefix(pfx)
}
}
if numUnlocked == 0 {
return false
}
s, err := b.IPSet()
if err != nil {
// Shouldn't happen, but if it does, fail closed.
return true
}
for _, m := range packetFilter {
for _, r := range m.Srcs {
if !s.OverlapsPrefix(r) {
continue
}
if len(m.Dsts) != 0 {
return true
}
}
}
return false
}
// TODO(nickkhyl): this should be non-existent with a proper [LocalBackend.updateFilterLocked].
// See the comment in that function for more details.
func (b *LocalBackend) setFilter(f *filter.Filter) {
b.currentNode().setFilter(f)
b.e.SetFilter(f)
if ms, ok := b.sys.MagicSock.GetOK(); ok {
ms.SetFilter(f)
}
}
var removeFromDefaultRoute = []netip.Prefix{
// RFC1918 LAN ranges
netip.MustParsePrefix("192.168.0.0/16"),
netip.MustParsePrefix("172.16.0.0/12"),
netip.MustParsePrefix("10.0.0.0/8"),
// IPv4 link-local
netip.MustParsePrefix("169.254.0.0/16"),
// IPv4 multicast
netip.MustParsePrefix("224.0.0.0/4"),
// Tailscale IPv4 range
tsaddr.CGNATRange(),
// IPv6 Link-local addresses
netip.MustParsePrefix("fe80::/10"),
// IPv6 multicast
netip.MustParsePrefix("ff00::/8"),
// Tailscale IPv6 range
tsaddr.TailscaleULARange(),
}
// internalAndExternalInterfaces splits interface routes into "internal"
// and "external" sets. Internal routes are those of virtual ethernet
// network interfaces used by guest VMs and containers, such as WSL and
// Docker.
//
// Given that "internal" routes don't leave the device, we choose to
// trust them more, allowing access to them when an Exit Node is enabled.
func internalAndExternalInterfaces() (internal, external []netip.Prefix, err error) {
il, err := netmon.GetInterfaceList()
if err != nil {
return nil, nil, err
}
return internalAndExternalInterfacesFrom(il, runtime.GOOS)
}
func internalAndExternalInterfacesFrom(il netmon.InterfaceList, goos string) (internal, external []netip.Prefix, err error) {
// We use an IPSetBuilder here to canonicalize the prefixes
// and to remove any duplicate entries.
var internalBuilder, externalBuilder netipx.IPSetBuilder
if err := il.ForeachInterfaceAddress(func(iface netmon.Interface, pfx netip.Prefix) {
if tsaddr.IsTailscaleIP(pfx.Addr()) {
return
}
if pfx.IsSingleIP() {
return
}
if iface.IsLoopback() {
internalBuilder.AddPrefix(pfx)
return
}
if goos == "windows" {
// Windows Hyper-V prefixes all MAC addresses with 00:15:5d.
// https://docs.microsoft.com/en-us/troubleshoot/windows-server/virtualization/default-limit-256-dynamic-mac-addresses
//
// This includes WSL2 vEthernet.
// Importantly: by default WSL2 /etc/resolv.conf points to
// a stub resolver running on the host vEthernet IP.
// So enabling exit nodes with the default tailnet
// configuration breaks WSL2 DNS without this.
mac := iface.Interface.HardwareAddr
if len(mac) == 6 && mac[0] == 0x00 && mac[1] == 0x15 && mac[2] == 0x5d {
internalBuilder.AddPrefix(pfx)
return
}
}
externalBuilder.AddPrefix(pfx)
}); err != nil {
return nil, nil, err
}
iSet, err := internalBuilder.IPSet()
if err != nil {
return nil, nil, err
}
eSet, err := externalBuilder.IPSet()
if err != nil {
return nil, nil, err
}
return iSet.Prefixes(), eSet.Prefixes(), nil
}
func interfaceRoutes() (ips *netipx.IPSet, hostIPs []netip.Addr, err error) {
var b netipx.IPSetBuilder
if err := netmon.ForeachInterfaceAddress(func(_ netmon.Interface, pfx netip.Prefix) {
if tsaddr.IsTailscaleIP(pfx.Addr()) {
return
}
if pfx.IsSingleIP() {
return
}
hostIPs = append(hostIPs, pfx.Addr())
b.AddPrefix(pfx)
}); err != nil {
return nil, nil, err
}
ipSet, _ := b.IPSet()
return ipSet, hostIPs, nil
}
// shrinkDefaultRoute returns an IPSet representing the IPs in route,
// minus those in removeFromDefaultRoute and localInterfaceRoutes,
// plus the IPs in hostIPs.
func shrinkDefaultRoute(route netip.Prefix, localInterfaceRoutes *netipx.IPSet, hostIPs []netip.Addr) (*netipx.IPSet, error) {
var b netipx.IPSetBuilder
// Add the default route.
b.AddPrefix(route)
// Remove the local interface routes.
b.RemoveSet(localInterfaceRoutes)
// Having removed all the LAN subnets, re-add the hosts's own
// IPs. It's fine for clients to connect to an exit node's public
// IP address, just not the attached subnet.
//
// Truly forbidden subnets (in removeFromDefaultRoute) will still
// be stripped back out by the next step.
for _, ip := range hostIPs {
if route.Contains(ip) {
b.Add(ip)
}
}
for _, pfx := range removeFromDefaultRoute {
b.RemovePrefix(pfx)
}
return b.IPSet()
}
// GetPushDeviceToken returns the push notification device token.
func (b *LocalBackend) GetPushDeviceToken() string {
return b.pushDeviceToken.Load()
}
// SetPushDeviceToken sets the push notification device token and informs the
// controlclient of the new value.
func (b *LocalBackend) SetPushDeviceToken(tk string) {
old := b.pushDeviceToken.Swap(tk)
if old == tk {
return
}
b.doSetHostinfoFilterServices()
}
func applyConfigToHostinfo(hi *tailcfg.Hostinfo, c *conffile.Config) {
if c == nil {
return
}
if c.Parsed.Hostname != nil {
hi.Hostname = *c.Parsed.Hostname
}
}
// WatchNotifications subscribes to the ipn.Notify message bus notification
// messages.
//
// WatchNotifications blocks until ctx is done.
//
// The provided onWatchAdded, if non-nil, will be called once the watcher
// is installed.
//
// The provided fn will be called for each notification. It will only be
// called with non-nil pointers. The caller must not modify roNotify. If
// fn returns false, the watch also stops.
//
// Failure to consume many notifications in a row will result in dropped
// notifications. There is currently (2022-11-22) no mechanism provided to
// detect when a message has been dropped.
func (b *LocalBackend) WatchNotifications(ctx context.Context, mask ipn.NotifyWatchOpt, onWatchAdded func(), fn func(roNotify *ipn.Notify) (keepGoing bool)) {
b.WatchNotificationsAs(ctx, nil, mask, onWatchAdded, fn)
}
// WatchNotificationsAs is like [LocalBackend.WatchNotifications] but takes an [ipnauth.Actor]
// as an additional parameter. If non-nil, the specified callback is invoked
// only for notifications relevant to this actor.
func (b *LocalBackend) WatchNotificationsAs(ctx context.Context, actor ipnauth.Actor, mask ipn.NotifyWatchOpt, onWatchAdded func(), fn func(roNotify *ipn.Notify) (keepGoing bool)) {
ch := make(chan *ipn.Notify, 128)
sessionID := rands.HexString(16)
if mask&ipn.NotifyHealthActions == 0 {
// if UI does not support PrimaryAction in health warnings, append
// action URLs to the warning text instead.
fn = appendHealthActions(fn)
}
var ini *ipn.Notify
b.mu.Lock()
const initialBits = ipn.NotifyInitialState | ipn.NotifyInitialPrefs | ipn.NotifyInitialNetMap | ipn.NotifyInitialDriveShares | ipn.NotifyInitialSuggestedExitNode | ipn.NotifyInitialClientVersion
if mask&initialBits != 0 {
cn := b.currentNode()
ini = &ipn.Notify{Version: version.Long()}
if mask&ipn.NotifyInitialState != 0 {
ini.SessionID = sessionID
ini.State = new(b.state)
if b.state == ipn.NeedsLogin && b.authURL != "" {
ini.BrowseToURL = new(b.authURL)
}
}
if mask&ipn.NotifyInitialPrefs != 0 {
ini.Prefs = new(b.sanitizedPrefsLocked())
}
if mask&ipn.NotifyInitialNetMap != 0 {
ini.NetMap = cn.NetMap()
}
if mask&ipn.NotifyInitialDriveShares != 0 && b.DriveSharingEnabled() {
ini.DriveShares = b.pm.prefs.DriveShares()
}
if mask&ipn.NotifyInitialHealthState != 0 {
ini.Health = b.HealthTracker().CurrentState()
}
if mask&ipn.NotifyInitialSuggestedExitNode != 0 {
if en, err := b.suggestExitNodeLocked(); err == nil {
ini.SuggestedExitNode = &en.ID
}
}
if mask&ipn.NotifyInitialClientVersion != 0 {
if prefs := b.pm.CurrentPrefs(); prefs.Valid() && prefs.AutoUpdate().Check {
ini.ClientVersion = b.lastClientVersion
}
}
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
session := &watchSession{
ch: ch,
owner: actor,
sessionID: sessionID,
cancel: cancel,
mask: mask,
}
mak.Set(&b.notifyWatchers, sessionID, session)
b.mu.Unlock()
metricCurrentWatchIPNBus.Add(1)
defer metricCurrentWatchIPNBus.Add(-1)
defer func() {
b.mu.Lock()
delete(b.notifyWatchers, sessionID)
b.mu.Unlock()
}()
if onWatchAdded != nil {
onWatchAdded()
}
if ini != nil {
if !fn(ini) {
return
}
}
// The GUI clients want to know when peers become active or inactive.
// They've historically got this information by polling for it, which is
// wasteful. As a step towards making it efficient, they now set this
// NotifyWatchEngineUpdates bit to ask for us to send it to them only on
// change. That's not yet (as of 2022-11-26) plumbed everywhere in
// tailscaled yet, so just do the polling here. This ends up causing all IPN
// bus watchers to get the notification every 2 seconds instead of just the
// GUI client's bus watcher, but in practice there's only 1 total connection
// anyway. And if we're polling, at least the client isn't making a new HTTP
// request every 2 seconds.
// TODO(bradfitz): plumb this further and only send a Notify on change.
if mask&ipn.NotifyWatchEngineUpdates != 0 {
b.goTracker.Go(func() { b.pollRequestEngineStatus(ctx) })
}
// TODO(marwan-at-work): streaming background logs?
defer b.DeleteForegroundSession(sessionID)
sender := &rateLimitingBusSender{fn: fn}
defer sender.close()
if mask&ipn.NotifyRateLimit != 0 {
sender.interval = 3 * time.Second
}
sender.Run(ctx, ch)
}
// appendHealthActions returns an IPN listener func that wraps the supplied IPN
// listener func and transforms health messages passed to the wrapped listener.
// If health messages with PrimaryActions are present, it appends the label &
// url in the PrimaryAction to the text of the message. For use for clients that
// do not process the PrimaryAction.
func appendHealthActions(fn func(roNotify *ipn.Notify) (keepGoing bool)) func(*ipn.Notify) bool {
return func(n *ipn.Notify) bool {
if n.Health == nil || len(n.Health.Warnings) == 0 {
return fn(n)
}
// Shallow clone the notify and health so we can mutate them
h2 := *n.Health
n2 := *n
n2.Health = &h2
n2.Health.Warnings = make(map[health.WarnableCode]health.UnhealthyState, len(n.Health.Warnings))
for k, v := range n.Health.Warnings {
if v.PrimaryAction != nil {
v.Text = fmt.Sprintf("%s %s: %s", v.Text, v.PrimaryAction.Label, v.PrimaryAction.URL)
v.PrimaryAction = nil
}
n2.Health.Warnings[k] = v
}
return fn(&n2)
}
}
// pollRequestEngineStatus calls b.e.RequestStatus every 2 seconds until ctx
// is done.
func (b *LocalBackend) pollRequestEngineStatus(ctx context.Context) {
ticker, tickerChannel := b.clock.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-tickerChannel:
b.e.RequestStatus()
case <-ctx.Done():
return
}
}
}
// DebugNotify injects a fake notify message to clients.
//
// It should only be used via the LocalAPI's debug handler.
func (b *LocalBackend) DebugNotify(n ipn.Notify) {
b.send(n)
}
// DebugNotifyLastNetMap injects a fake notify message to clients,
// repeating whatever the last netmap was.
//
// It should only be used via the LocalAPI's debug handler.
func (b *LocalBackend) DebugNotifyLastNetMap() {
if nm := b.currentNode().NetMap(); nm != nil {
b.send(ipn.Notify{NetMap: nm})
}
}
// DebugForceNetmapUpdate forces a full no-op netmap update of the current
// netmap in all the various subsystems (wireguard, magicsock, LocalBackend).
//
// It exists for load testing reasons (for issue 1909), doing what would happen
// if a new MapResponse came in from the control server that couldn't be handled
// incrementally.
func (b *LocalBackend) DebugForceNetmapUpdate() {
b.mu.Lock()
defer b.mu.Unlock()
// TODO(nickkhyl): this all should be done in [LocalBackend.setNetMapLocked].
nm := b.currentNode().NetMap()
b.e.SetNetworkMap(nm)
if nm != nil {
b.MagicConn().SetDERPMap(nm.DERPMap)
}
b.setNetMapLocked(nm)
}
// DebugPickNewDERP forwards to magicsock.Conn.DebugPickNewDERP.
// See its docs.
func (b *LocalBackend) DebugPickNewDERP() error {
return b.sys.MagicSock.Get().DebugPickNewDERP()
}
// DebugForcePreferDERP forwards to netcheck.DebugForcePreferDERP.
// See its docs.
func (b *LocalBackend) DebugForcePreferDERP(n int) {
b.sys.MagicSock.Get().DebugForcePreferDERP(n)
}
// send delivers n to the connected frontend and any API watchers from
// LocalBackend.WatchNotifications (via the LocalAPI).
//
// If no frontend is connected or API watchers are backed up, the notification
// is dropped without being delivered.
//
// If n contains Prefs, those will be sanitized before being delivered.
//
// b.mu must not be held.
func (b *LocalBackend) send(n ipn.Notify) {
b.sendTo(n, allClients)
}
func (b *LocalBackend) sendLocked(n ipn.Notify) {
b.sendToLocked(n, allClients)
}
// SendNotify sends a notification to the IPN bus,
// typically to the GUI client.
func (b *LocalBackend) SendNotify(n ipn.Notify) {
b.send(n)
}
// notificationTarget describes a notification recipient.
// A zero value is valid and indicate that the notification
// should be broadcast to all active [watchSession]s.
type notificationTarget struct {
// userID is the OS-specific UID of the target user.
// If empty, the notification is not user-specific and
// will be broadcast to all connected users.
// TODO(nickkhyl): make this field cross-platform rather
// than Windows-specific.
userID ipn.WindowsUserID
// clientID identifies a client that should be the exclusive recipient
// of the notification. A zero value indicates that notification should
// be sent to all sessions of the specified user.
clientID ipnauth.ClientID
}
var allClients = notificationTarget{} // broadcast to all connected clients
// toNotificationTarget returns a [notificationTarget] that matches only actors
// representing the same user as the specified actor. If the actor represents
// a specific connected client, the [ipnauth.ClientID] must also match.
// If the actor is nil, the [notificationTarget] matches all actors.
func toNotificationTarget(actor ipnauth.Actor) notificationTarget {
t := notificationTarget{}
if actor != nil {
t.userID = actor.UserID()
t.clientID, _ = actor.ClientID()
}
return t
}
// match reports whether the specified actor should receive notifications
// targeting t. If the actor is nil, it should only receive notifications
// intended for all users.
func (t notificationTarget) match(actor ipnauth.Actor) bool {
if t == allClients {
return true
}
if actor == nil {
return false
}
if t.userID != "" && t.userID != actor.UserID() {
return false
}
if t.clientID != ipnauth.NoClientID {
clientID, ok := actor.ClientID()
if !ok || clientID != t.clientID {
return false
}
}
return true
}
// sendTo is like [LocalBackend.send] but allows specifying a recipient.
func (b *LocalBackend) sendTo(n ipn.Notify, recipient notificationTarget) {
b.mu.Lock()
defer b.mu.Unlock()
b.sendToLocked(n, recipient)
}
// sendToLocked is like [LocalBackend.sendTo], but assumes b.mu is already held.
func (b *LocalBackend) sendToLocked(n ipn.Notify, recipient notificationTarget) {
if n.Prefs != nil {
n.Prefs = new(stripKeysFromPrefs(*n.Prefs))
}
if n.Version == "" {
n.Version = version.Long()
}
for _, f := range b.extHost.Hooks().MutateNotifyLocked {
f(&n)
}
for _, sess := range b.notifyWatchers {
if !recipient.match(sess.owner) {
continue
}
nOut := &n
if n.PeerChanges != nil {
// Take a shallow copy of n so we can elide the PeerChanges or the Netmap
// based on the session's mask.
nOut = new(n)
if sess.mask&ipn.NotifyPeerChanges != 0 {
// Skip the full Netmap
nOut.NetMap = nil
} else {
// Skip the PeerChanges
nOut.PeerChanges = nil
}
}
select {
case sess.ch <- nOut:
default:
// Drop the notification if the channel is full.
}
}
}
// setAuthURLLocked sets the authURL and triggers [LocalBackend.popBrowserAuthNow] if the URL has changed.
// This method is called when a new authURL is received from the control plane, meaning that either a user
// has started a new interactive login (e.g., by running `tailscale login` or clicking Login in the GUI),
// or the control plane was unable to authenticate this node non-interactively (e.g., due to key expiration).
// A non-nil b.authActor indicates that an interactive login is in progress and was initiated by the specified actor.
//
// b.mu must be held.
//
// If url is "", it is equivalent to calling [LocalBackend.resetAuthURLLocked] with b.mu held.
func (b *LocalBackend) setAuthURLLocked(url string) {
var popBrowser, keyExpired bool
var recipient ipnauth.Actor
switch {
case url == "":
b.resetAuthURLLocked()
return
case b.authURL != url:
b.authURL = url
b.authURLTime = b.clock.Now()
// Always open the browser if the URL has changed.
// This includes the transition from no URL -> some URL.
popBrowser = true
default:
// Otherwise, only open it if the user explicitly requests interactive login.
popBrowser = b.authActor != nil
}
keyExpired = b.keyExpired
recipient = b.authActor // or nil
// Consume the StartLoginInteractive call, if any, that caused the control
// plane to send us this URL.
b.authActor = nil
if popBrowser {
b.popBrowserAuthNowLocked(url, keyExpired, recipient)
}
}
// popBrowserAuthNowLocked shuts down the data plane and sends the URL to the recipient's
// [watchSession]s if the recipient is non-nil; otherwise, it sends the URL to all watchSessions.
// keyExpired is the value of b.keyExpired upon entry and indicates
// whether the node's key has expired.
//
// b.mu must be held.
func (b *LocalBackend) popBrowserAuthNowLocked(url string, keyExpired bool, recipient ipnauth.Actor) {
b.logf("popBrowserAuthNow(%q): url=%v, key-expired=%v, seamless-key-renewal=%v", maybeUsernameOf(recipient), url != "", keyExpired, b.seamlessRenewalEnabled())
// Deconfigure the local network data plane if:
// - seamless key renewal is not enabled;
// - key is expired (in which case tailnet connectivity is down anyway).
if !b.seamlessRenewalEnabled() || keyExpired {
b.blockEngineUpdatesLocked(true)
b.stopEngineAndWaitLocked()
if b.state == ipn.Running {
b.enterStateLocked(ipn.Starting)
}
}
b.tellRecipientToBrowseToURLLocked(url, toNotificationTarget(recipient))
}
// validPopBrowserURL reports whether urlStr is a valid value for a
// control server to send in a *URL field.
//
// b.mu must *not* be held.
func (b *LocalBackend) validPopBrowserURL(urlStr string) bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.validPopBrowserURLLocked(urlStr)
}
// validPopBrowserURLLocked reports whether urlStr is a valid value for a
// control server to send in a *URL field.
//
// b.mu must be held.
func (b *LocalBackend) validPopBrowserURLLocked(urlStr string) bool {
if urlStr == "" {
return false
}
u, err := url.Parse(urlStr)
if err != nil {
return false
}
serverURL := b.sanitizedPrefsLocked().ControlURLOrDefault(b.polc)
if ipn.IsLoginServerSynonym(serverURL) {
// When connected to the official Tailscale control plane, only allow
// URLs from tailscale.com or its subdomains.
if h := u.Hostname(); h != "tailscale.com" && !strings.HasSuffix(u.Hostname(), ".tailscale.com") {
return false
}
// When using a different ControlURL, we cannot be sure what legitimate
// PopBrowserURLs they will send. Allow any domain there to avoid
// breaking existing user setups.
}
switch u.Scheme {
case "https":
return true
case "http":
// If the control server is using plain HTTP (likely a dev server),
// then permit http://.
return strings.HasPrefix(serverURL, "http://")
}
return false
}
func (b *LocalBackend) tellClientToBrowseToURL(url string) {
b.mu.Lock()
defer b.mu.Unlock()
b.tellRecipientToBrowseToURLLocked(url, allClients)
}
// tellRecipientToBrowseToURLLocked is like tellClientToBrowseToURL but allows specifying a recipient
// and b.mu must be held.
func (b *LocalBackend) tellRecipientToBrowseToURLLocked(url string, recipient notificationTarget) {
if b.validPopBrowserURLLocked(url) {
b.sendToLocked(ipn.Notify{BrowseToURL: &url}, recipient)
}
}
// onClientVersion is called on MapResponse updates when a MapResponse contains
// a non-nil ClientVersion message.
func (b *LocalBackend) onClientVersion(v *tailcfg.ClientVersion) {
b.mu.Lock()
defer b.mu.Unlock()
b.lastClientVersion = v
b.health.SetLatestVersion(v)
prefs := b.pm.CurrentPrefs()
if prefs.Valid() && prefs.AutoUpdate().Check {
b.sendLocked(ipn.Notify{ClientVersion: v})
}
}
func (b *LocalBackend) onTailnetDefaultAutoUpdate(au bool) {
b.mu.Lock()
defer b.mu.Unlock()
prefs := b.pm.CurrentPrefs()
if !prefs.Valid() {
b.logf("[unexpected]: received tailnet default auto-update callback but current prefs are nil")
return
}
if _, ok := prefs.AutoUpdate().Apply.Get(); ok {
// Apply was already set from a previous default or manually by the
// user. Tailnet default should not affect us, even if it changes.
return
}
if au && b.hostinfo != nil && b.hostinfo.Container.EqualBool(true) {
// This is a containerized node, which is usually meant to be
// immutable. Do not enable auto-updates if the tailnet does. But users
// can still manually enable auto-updates on this node.
return
}
if buildfeatures.HasClientUpdate && feature.CanAutoUpdate() {
b.logf("using tailnet default auto-update setting: %v", au)
prefsClone := prefs.AsStruct()
prefsClone.AutoUpdate.Apply = opt.NewBool(au)
_, err := b.editPrefsLocked(
ipnauth.Self,
&ipn.MaskedPrefs{
Prefs: *prefsClone,
AutoUpdateSet: ipn.AutoUpdatePrefsMask{
ApplySet: true,
},
})
if err != nil {
b.logf("failed to apply tailnet-wide default for auto-updates (%v): %v", au, err)
return
}
}
}
// For testing lazy machine key generation.
var panicOnMachineKeyGeneration = envknob.RegisterBool("TS_DEBUG_PANIC_MACHINE_KEY")
func (b *LocalBackend) createGetMachinePrivateKeyFunc() func() (key.MachinePrivate, error) {
var cache syncs.AtomicValue[key.MachinePrivate]
return func() (key.MachinePrivate, error) {
if panicOnMachineKeyGeneration() {
panic("machine key generated")
}
if v, ok := cache.LoadOk(); ok {
return v, nil
}
b.mu.Lock()
defer b.mu.Unlock()
if v, ok := cache.LoadOk(); ok {
return v, nil
}
if err := b.initMachineKeyLocked(); err != nil {
return key.MachinePrivate{}, err
}
cache.Store(b.machinePrivKey)
return b.machinePrivKey, nil
}
}
// initMachineKeyLocked is called to initialize b.machinePrivKey.
//
// b.prefs must already be initialized.
// b.stateKey should be set too, but just for nicer log messages.
// b.mu must be held.
func (b *LocalBackend) initMachineKeyLocked() (err error) {
if !b.machinePrivKey.IsZero() {
// Already set.
return nil
}
keyText, err := b.store.ReadState(ipn.MachineKeyStateKey)
if err == nil {
if err := b.machinePrivKey.UnmarshalText(keyText); err != nil {
return fmt.Errorf("invalid key in %s key of %v: %w", ipn.MachineKeyStateKey, b.store, err)
}
if b.machinePrivKey.IsZero() {
return fmt.Errorf("invalid zero key stored in %v key of %v", ipn.MachineKeyStateKey, b.store)
}
return nil
}
if err != ipn.ErrStateNotExist {
return fmt.Errorf("error reading %v key of %v: %w", ipn.MachineKeyStateKey, b.store, err)
}
// If we didn't find one already on disk and the prefs already
// have a legacy machine key, use that. Otherwise generate a
// new one.
b.logf("generating new machine key")
b.machinePrivKey = key.NewMachine()
keyText, _ = b.machinePrivKey.MarshalText()
if err := ipn.WriteState(b.store, ipn.MachineKeyStateKey, keyText); err != nil {
b.logf("error writing machine key to store: %v", err)
return err
}
b.logf("machine key written to store")
return nil
}
// clearMachineKeyLocked is called to clear the persisted and in-memory
// machine key, so that initMachineKeyLocked (called as part of starting)
// generates a new machine key.
//
// b.mu must be held.
func (b *LocalBackend) clearMachineKeyLocked() error {
if err := ipn.WriteState(b.store, ipn.MachineKeyStateKey, nil); err != nil {
return err
}
b.machinePrivKey = key.MachinePrivate{}
b.logf("machine key cleared")
return nil
}
func generateInterceptTCPPortFunc(ports []uint16) func(uint16) bool {
slices.Sort(ports)
ports = slices.Compact(ports)
var f func(uint16) bool
switch len(ports) {
case 0:
f = func(uint16) bool { return false }
case 1:
f = func(p uint16) bool { return ports[0] == p }
case 2:
f = func(p uint16) bool { return ports[0] == p || ports[1] == p }
case 3:
f = func(p uint16) bool { return ports[0] == p || ports[1] == p || ports[2] == p }
default:
if len(ports) > 16 {
m := map[uint16]bool{}
for _, p := range ports {
m[p] = true
}
f = func(p uint16) bool { return m[p] }
} else {
f = func(p uint16) bool {
return slices.Contains(ports, p)
}
}
}
return f
}
// setTCPPortsIntercepted populates b.shouldInterceptTCPPortAtomic with an
// efficient func for ShouldInterceptTCPPort to use, which is called on every
// incoming packet.
func (b *LocalBackend) setTCPPortsIntercepted(ports []uint16) {
b.shouldInterceptTCPPortAtomic.Store(generateInterceptTCPPortFunc(ports))
}
func generateInterceptVIPServicesTCPPortFunc(svcAddrPorts map[netip.Addr]func(uint16) bool) func(netip.AddrPort) bool {
return func(ap netip.AddrPort) bool {
if f, ok := svcAddrPorts[ap.Addr()]; ok {
return f(ap.Port())
}
return false
}
}
// setAtomicValuesFromPrefsLocked populates sshAtomicBool, containsViaIPFuncAtomic,
// shouldInterceptTCPPortAtomic, and exposeRemoteWebClientAtomicBool from the prefs p,
// which may be !Valid().
func (b *LocalBackend) setAtomicValuesFromPrefsLocked(p ipn.PrefsView) {
b.sshAtomicBool.Store(p.Valid() && p.RunSSH() && envknob.CanSSHD())
b.setExposeRemoteWebClientAtomicBoolLocked(p)
if !p.Valid() {
b.containsViaIPFuncAtomic.Store(ipset.FalseContainsIPFunc())
b.setTCPPortsIntercepted(nil)
if f, ok := hookServeClearVIPServicesTCPPortsInterceptedLocked.GetOk(); ok {
f(b)
}
b.lastServeConfJSON = mem.B(nil)
b.serveConfig = ipn.ServeConfigView{}
} else {
filtered := tsaddr.FilterPrefixesCopy(p.AdvertiseRoutes(), tsaddr.IsViaPrefix)
b.containsViaIPFuncAtomic.Store(ipset.NewContainsIPFunc(views.SliceOf(filtered)))
b.setTCPPortsInterceptedFromNetmapAndPrefsLocked(p)
}
}
// State returns the backend state machine's current state.
func (b *LocalBackend) State() ipn.State {
b.mu.Lock()
defer b.mu.Unlock()
return b.state
}
// CheckIPNConnectionAllowed returns an error if the specified actor should not
// be allowed to connect or make requests to the LocalAPI currently.
//
// Currently (as of 2024-08-26), this is only used on Windows.
// We plan to remove it as part of the multi-user and unattended mode improvements
// as we progress on tailscale/corp#18342.
func (b *LocalBackend) CheckIPNConnectionAllowed(actor ipnauth.Actor) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.pm.CurrentUserID() == "" {
// There's no "current user" yet; allow the connection.
return nil
}
// Always allow Windows SYSTEM user to connect,
// even if Tailscale is currently being used by another user.
if actor.IsLocalSystem() {
return nil
}
uid := actor.UserID()
if uid == "" {
return errors.New("empty user uid in connection identity")
}
if uid == b.pm.CurrentUserID() {
// The connection is from the current user; allow it.
return nil
}
// The connection is from a different user; block it.
var reason string
if b.pm.CurrentPrefs().ForceDaemon() {
reason = "running in server mode"
} else {
reason = "already in use"
}
return fmt.Errorf("Tailscale %s (%q); connection from %q not allowed",
reason, b.tryLookupUserName(string(b.pm.CurrentUserID())),
b.tryLookupUserName(string(uid)))
}
// tryLookupUserName tries to look up the username for the uid.
// It returns the username on success, or the UID on failure.
func (b *LocalBackend) tryLookupUserName(uid string) string {
u, err := ipnauth.LookupUserFromID(b.logf, uid)
if err != nil {
return uid
}
return u.Username
}
// StartLoginInteractive requests a new interactive login from controlclient,
// unless such a flow is already in progress, in which case
// StartLoginInteractive attempts to pick up the in-progress flow where it left
// off.
func (b *LocalBackend) StartLoginInteractive(ctx context.Context) error {
return b.StartLoginInteractiveAs(ctx, nil)
}
// StartLoginInteractiveAs is like StartLoginInteractive but takes an [ipnauth.Actor]
// as an additional parameter. If non-nil, the specified user is expected to complete
// the interactive login, and therefore will receive the BrowseToURL notification once
// the control plane sends us one. Otherwise, the notification will be delivered to all
// active [watchSession]s.
func (b *LocalBackend) StartLoginInteractiveAs(ctx context.Context, user ipnauth.Actor) error {
if b.health.IsUnhealthy(ipn.StateStoreHealth) {
return errors.New("cannot log in when state store is unhealthy")
}
b.mu.Lock()
defer b.mu.Unlock()
if b.cc == nil {
panic("LocalBackend.assertClient: b.cc == nil")
}
url := b.authURL
keyExpired := b.keyExpired
timeSinceAuthURLCreated := b.clock.Since(b.authURLTime)
// Only use an authURL if it was sent down from control in the last
// 6 days and 23 hours. Avoids using a stale URL that is no longer valid
// server-side. Server-side URLs expire after 7 days.
hasValidURL := url != "" && timeSinceAuthURLCreated < ((7*24*time.Hour)-(1*time.Hour))
if !hasValidURL {
// A user wants to log in interactively, but we don't have a valid authURL.
// Remember the user who initiated the login, so that we can notify them
// once the authURL is available.
b.authActor = user
}
cc := b.cc
b.logf("StartLoginInteractiveAs(%q): url=%v", maybeUsernameOf(user), hasValidURL)
if hasValidURL {
b.popBrowserAuthNowLocked(url, keyExpired, user)
} else {
cc.Login(b.loginFlags | controlclient.LoginInteractive)
}
return nil
}
func (b *LocalBackend) Ping(ctx context.Context, ip netip.Addr, pingType tailcfg.PingType, size int) (*ipnstate.PingResult, error) {
if pingType == tailcfg.PingPeerAPI {
t0 := b.clock.Now()
node, base, err := b.pingPeerAPI(ctx, ip)
if err != nil && ctx.Err() != nil {
return nil, ctx.Err()
}
d := b.clock.Since(t0)
pr := &ipnstate.PingResult{
IP: ip.String(),
NodeIP: ip.String(),
LatencySeconds: d.Seconds(),
PeerAPIURL: base,
}
if err != nil {
pr.Err = err.Error()
}
if node.Valid() {
pr.NodeName = node.Name()
}
return pr, nil
}
ch := make(chan *ipnstate.PingResult, 1)
b.e.Ping(ip, pingType, size, func(pr *ipnstate.PingResult) {
select {
case ch <- pr:
default:
}
})
select {
case pr := <-ch:
return pr, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (b *LocalBackend) pingPeerAPI(ctx context.Context, ip netip.Addr) (peer tailcfg.NodeView, peerBase string, err error) {
if !buildfeatures.HasPeerAPIClient {
return peer, peerBase, feature.ErrUnavailable
}
var zero tailcfg.NodeView
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
nm := b.NetMap()
if nm == nil {
return zero, "", errors.New("no netmap")
}
peer, ok := nm.PeerByTailscaleIP(ip)
if !ok {
return zero, "", fmt.Errorf("no peer found with Tailscale IP %v", ip)
}
if peer.Expired() {
return zero, "", errors.New("peer's node key has expired")
}
base := peerAPIBase(nm, peer)
if base == "" {
return zero, "", fmt.Errorf("no PeerAPI base found for peer %v (%v)", peer.ID(), ip)
}
outReq, err := http.NewRequestWithContext(ctx, "HEAD", base, nil)
if err != nil {
return zero, "", err
}
tr := b.Dialer().PeerAPITransport()
res, err := tr.RoundTrip(outReq)
if err != nil {
return zero, "", err
}
defer res.Body.Close() // but unnecessary on HEAD responses
if res.StatusCode != http.StatusOK {
return zero, "", fmt.Errorf("HTTP status %v", res.Status)
}
return peer, base, nil
}
// parseWgStatusLocked returns an EngineStatus based on s.
//
// b.mu must be held; mostly because the caller is about to anyway, and doing so
// gives us slightly better guarantees about the two peers stats lines not
// being intermixed if there are concurrent calls to our caller.
func (b *LocalBackend) parseWgStatusLocked(s *wgengine.Status) (ret ipn.EngineStatus) {
var peerStats, peerKeys strings.Builder
ret.LiveDERPs = s.DERPs
ret.LivePeers = map[key.NodePublic]ipnstate.PeerStatusLite{}
for _, p := range s.Peers {
if !p.LastHandshake.IsZero() {
fmt.Fprintf(&peerStats, "%d/%d ", p.RxBytes, p.TxBytes)
fmt.Fprintf(&peerKeys, "%s ", p.NodeKey.ShortString())
ret.NumLive++
ret.LivePeers[p.NodeKey] = p
}
ret.RBytes += p.RxBytes
ret.WBytes += p.TxBytes
}
// [GRINDER STATS LINES] - please don't remove (used for log parsing)
if peerStats.Len() > 0 {
b.keyLogf("[v1] peer keys: %s", strings.TrimSpace(peerKeys.String()))
b.statsLogf("[v1] v%v peers: %v", version.Long(), strings.TrimSpace(peerStats.String()))
}
return ret
}
// SetCurrentUser is used to implement support for multi-user systems (only
// Windows 2022-11-25). On such systems, the actor is used to determine which
// user's state should be used. The current user is maintained by active
// connections open to the backend.
//
// When the backend initially starts it will typically start with no user. Then,
// the first connection to the backend from the GUI frontend will set the
// current user. Once set, the current user cannot be changed until all previous
// connections are closed. The user is also used to determine which
// LoginProfiles are accessible.
//
// In unattended mode, the backend will start with the user which enabled
// unattended mode. The user must disable unattended mode before the user can be
// changed.
//
// On non-multi-user systems, the actor should be set to nil.
func (b *LocalBackend) SetCurrentUser(actor ipnauth.Actor) {
b.mu.Lock()
defer b.mu.Unlock()
var userIdentifier string
if user := cmp.Or(actor, b.currentUser); user != nil {
maybeUsername, _ := user.Username()
userIdentifier = cmp.Or(maybeUsername, string(user.UserID()))
}
if actor != b.currentUser {
if c, ok := b.currentUser.(ipnauth.ActorCloser); ok {
c.Close()
}
b.currentUser = actor
}
var action string
if actor == nil {
action = "disconnected"
} else {
action = "connected"
}
reason := fmt.Sprintf("client %s (%s)", action, userIdentifier)
b.switchToBestProfileLocked(reason)
}
// SwitchToBestProfile selects the best profile to use,
// as reported by [LocalBackend.resolveBestProfileLocked], and switches
// to it, unless it's already the current profile. The reason indicates
// why the profile is being switched, such as due to a client connecting
// or disconnecting, or a change in the desktop session state, and is used
// for logging.
func (b *LocalBackend) SwitchToBestProfile(reason string) {
b.mu.Lock()
defer b.mu.Unlock()
b.switchToBestProfileLocked(reason)
}
// switchToBestProfileLocked is like [LocalBackend.SwitchToBestProfile],
// but b.mu must held on entry.
func (b *LocalBackend) switchToBestProfileLocked(reason string) {
oldControlURL := b.pm.CurrentPrefs().ControlURLOrDefault(b.polc)
profile, background := b.resolveBestProfileLocked()
cp, switched, err := b.pm.SwitchToProfile(profile)
switch {
case !switched && cp.ID() == "":
if err != nil {
b.logf("%s: an error occurred; staying on empty profile: %v", reason, err)
} else {
b.logf("%s: staying on empty profile", reason)
}
case !switched:
if err != nil {
b.logf("%s: an error occurred; staying on profile %q (%s): %v", reason, cp.UserProfile().LoginName, cp.ID(), err)
} else {
b.logf("%s: staying on profile %q (%s)", reason, cp.UserProfile().LoginName, cp.ID())
}
case cp.ID() == "":
b.logf("%s: disconnecting Tailscale", reason)
case background:
b.logf("%s: switching to background profile %q (%s)", reason, cp.UserProfile().LoginName, cp.ID())
default:
b.logf("%s: switching to profile %q (%s)", reason, cp.UserProfile().LoginName, cp.ID())
}
if !switched {
return
}
// As an optimization, only reset the dialPlan if the control URL changed.
if newControlURL := b.pm.CurrentPrefs().ControlURLOrDefault(b.polc); oldControlURL != newControlURL {
b.resetDialPlan()
}
if err := b.resetForProfileChangeLocked(); err != nil {
// TODO(nickkhyl): The actual reset cannot fail. However,
// the TKA initialization or [LocalBackend.Start] can fail.
// These errors are not critical as far as we're concerned.
// But maybe we should post a notification to the API watchers?
b.logf("failed switching profile to %q: %v", profile.ID(), err)
}
}
// resolveBestProfileLocked returns the best profile to use based on the current
// state of the backend, such as whether a GUI/CLI client is connected, whether
// the unattended mode is enabled, the current state of the desktop sessions,
// and other factors.
//
// It returns a read-only view of the profile and whether it is considered
// a background profile. A background profile is used when no OS user is actively
// using Tailscale, such as when no GUI/CLI client is connected and Unattended Mode
// is enabled (see also [LocalBackend.getBackgroundProfileLocked]).
//
// An invalid view indicates no profile, meaning Tailscale should disconnect
// and remain idle until a GUI or CLI client connects.
// A valid profile view with an empty [ipn.ProfileID] indicates a new profile that
// has not been persisted yet.
//
// b.mu must be held.
func (b *LocalBackend) resolveBestProfileLocked() (_ ipn.LoginProfileView, isBackground bool) {
// TODO(nickkhyl): delegate all of this to the extensions and remove the distinction
// between "foreground" and "background" profiles as we migrate away from the concept
// of a single "current user" on Windows. See tailscale/corp#18342.
//
// If a GUI/CLI client is connected, use the connected user's profile, which means
// either the current profile if owned by the user, or their default profile.
if b.currentUser != nil {
profile := b.pm.CurrentProfile()
// TODO(nickkhyl): check if the current profile is allowed on the device,
// such as when [pkey.Tailnet] policy setting requires a specific Tailnet.
// See tailscale/corp#26249.
if uid := b.currentUser.UserID(); profile.LocalUserID() != uid {
profile = b.pm.DefaultUserProfile(uid)
}
return profile, false
}
// Otherwise, if on Windows, use the background profile if one is set.
// This includes staying on the current profile if Unattended Mode is enabled
// or if AlwaysOn mode is enabled and the current user is still signed in.
// If the returned background profileID is "", Tailscale will disconnect
// and remain idle until a GUI or CLI client connects.
if goos := envknob.GOOS(); goos == "windows" {
// If Unattended Mode is enabled for the current profile, keep using it.
if b.pm.CurrentPrefs().ForceDaemon() {
return b.pm.CurrentProfile(), true
}
// Otherwise, use the profile returned by the extension.
profile := b.extHost.DetermineBackgroundProfile(b.pm)
return profile, true
}
// On other platforms, however, Tailscale continues to run in the background
// using the current profile.
//
// TODO(nickkhyl): check if the current profile is allowed on the device,
// such as when [pkey.Tailnet] policy setting requires a specific Tailnet.
// See tailscale/corp#26249.
return b.pm.CurrentProfile(), false
}
// CurrentUserForTest returns the current user and the associated WindowsUserID.
// It is used for testing only, and will be removed along with the rest of the
// "current user" functionality as we progress on the multi-user improvements (tailscale/corp#18342).
func (b *LocalBackend) CurrentUserForTest() (ipn.WindowsUserID, ipnauth.Actor) {
testenv.AssertInTest()
b.mu.Lock()
defer b.mu.Unlock()
return b.pm.CurrentUserID(), b.currentUser
}
func (b *LocalBackend) CheckPrefs(p *ipn.Prefs) error {
b.mu.Lock()
defer b.mu.Unlock()
return b.checkPrefsLocked(p)
}
// isConfigLocked_Locked reports whether the parsed config file is locked.
// b.mu must be held.
func (b *LocalBackend) isConfigLocked_Locked() bool {
// TODO(bradfitz,maisem): make this more fine-grained, permit changing
// some things if they're not explicitly set in the config. But for now
// (2023-10-16), just blanket disable everything.
return b.conf != nil && !b.conf.Parsed.Locked.EqualBool(false)
}
func (b *LocalBackend) checkPrefsLocked(p *ipn.Prefs) error {
if b.isConfigLocked_Locked() {
return errors.New("can't reconfigure tailscaled when using a config file; config file is locked")
}
var errs []error
if p.Hostname == "badhostname.tailscale." {
// Keep this one just for testing.
errs = append(errs, errors.New("bad hostname [test]"))
}
if err := b.checkProfileNameLocked(p); err != nil {
errs = append(errs, err)
}
if err := b.checkSSHPrefsLocked(p); err != nil {
errs = append(errs, err)
}
if err := b.checkExitNodePrefsLocked(p); err != nil {
errs = append(errs, err)
}
if err := b.checkFunnelEnabledLocked(p); err != nil {
errs = append(errs, err)
}
if err := b.checkAutoUpdatePrefsLocked(p); err != nil {
errs = append(errs, err)
}
if err := checkAdvertiseRoutes(p); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}
func (b *LocalBackend) checkSSHPrefsLocked(p *ipn.Prefs) error {
if !p.RunSSH {
return nil
}
if err := featureknob.CanRunTailscaleSSH(); err != nil {
return err
}
if runtime.GOOS == "linux" {
b.updateSELinuxHealthWarning()
}
if envknob.SSHIgnoreTailnetPolicy() || envknob.SSHPolicyFile() != "" {
return nil
}
// Assume that we do have the SSH capability if don't have a netmap yet.
if !b.currentNode().SelfHasCapOr(tailcfg.CapabilitySSH, true) {
if b.isDefaultServerLocked() {
return errors.New("Unable to enable local Tailscale SSH server; not enabled on Tailnet. See https://tailscale.com/s/ssh")
}
return errors.New("Unable to enable local Tailscale SSH server; not enabled on Tailnet.")
}
return nil
}
func (b *LocalBackend) sshOnButUnusableHealthCheckMessageLocked() (healthMessage string) {
if p := b.pm.CurrentPrefs(); !p.Valid() || !p.RunSSH() {
return ""
}
if envknob.SSHIgnoreTailnetPolicy() || envknob.SSHPolicyFile() != "" {
return "development SSH policy in use"
}
nm := b.currentNode().NetMap()
if nm == nil {
return ""
}
if nm.SSHPolicy != nil && len(nm.SSHPolicy.Rules) > 0 {
return ""
}
isDefault := b.isDefaultServerLocked()
if !nm.HasCap(tailcfg.CapabilityAdmin) {
return healthmsg.TailscaleSSHOnBut + "access controls don't allow anyone to access this device. Ask your admin to update your tailnet's ACLs to allow access."
}
if !isDefault {
return healthmsg.TailscaleSSHOnBut + "access controls don't allow anyone to access this device. Update your tailnet's ACLs to allow access."
}
return healthmsg.TailscaleSSHOnBut + "access controls don't allow anyone to access this device. Update your tailnet's ACLs at https://tailscale.com/s/ssh-policy"
}
func (b *LocalBackend) isDefaultServerLocked() bool {
prefs := b.pm.CurrentPrefs()
if !prefs.Valid() {
return true // assume true until set otherwise
}
return prefs.ControlURLOrDefault(b.polc) == ipn.DefaultControlURL
}
func (b *LocalBackend) checkExitNodePrefsLocked(p *ipn.Prefs) error {
tryingToUseExitNode := p.ExitNodeIP.IsValid() || p.ExitNodeID != ""
if !tryingToUseExitNode {
return nil
}
if !buildfeatures.HasUseExitNode {
return feature.ErrUnavailable
}
if err := featureknob.CanUseExitNode(); err != nil {
return err
}
if p.AdvertisesExitNode() {
return errors.New("Cannot advertise an exit node and use an exit node at the same time.")
}
return nil
}
func (b *LocalBackend) checkFunnelEnabledLocked(p *ipn.Prefs) error {
if p.ShieldsUp && b.serveConfig.IsFunnelOn() {
return errors.New("Cannot enable shields-up when Funnel is enabled.")
}
return nil
}
func (b *LocalBackend) checkAutoUpdatePrefsLocked(p *ipn.Prefs) error {
if !buildfeatures.HasClientUpdate {
if p.AutoUpdate.Apply.EqualBool(true) {
return errors.New("Auto-update support is disabled in this build")
}
}
if p.AutoUpdate.Apply.EqualBool(true) && !feature.CanAutoUpdate() {
return errors.New("Auto-updates are not supported on this platform.")
}
return nil
}
// checkAdvertiseRoutes validates that all advertised routes have
// properly masked prefixes (no non-address bits set).
func checkAdvertiseRoutes(p *ipn.Prefs) error {
var errs []error
for _, route := range p.AdvertiseRoutes {
if route != route.Masked() {
errs = append(errs, fmt.Errorf("route %s has non-address bits set; expected %s", route, route.Masked()))
}
}
return errors.Join(errs...)
}
// SetUseExitNodeEnabled turns on or off the most recently selected exit node.
//
// On success, it returns the resulting prefs (or current prefs, in the case of no change).
// Setting the value to false when use of an exit node is already false is not an error,
// nor is true when the exit node is already in use.
func (b *LocalBackend) SetUseExitNodeEnabled(actor ipnauth.Actor, v bool) (ipn.PrefsView, error) {
b.mu.Lock()
defer b.mu.Unlock()
p0 := b.pm.CurrentPrefs()
if !buildfeatures.HasUseExitNode {
return p0, nil
}
if v && p0.ExitNodeID() != "" {
// Already on.
return p0, nil
}
if !v && p0.ExitNodeID() == "" {
// Already off.
return p0, nil
}
var zero ipn.PrefsView
if v && p0.InternalExitNodePrior() == "" {
if !p0.ExitNodeIP().IsValid() {
return zero, errors.New("no exit node IP to enable & prior exit node IP was never resolved an a node")
}
return zero, errors.New("no prior exit node to enable")
}
mp := &ipn.MaskedPrefs{}
if v {
mp.ExitNodeIDSet = true
mp.ExitNodeID = p0.InternalExitNodePrior()
if expr, ok := ipn.ParseAutoExitNodeString(mp.ExitNodeID); ok {
mp.AutoExitNodeSet = true
mp.AutoExitNode = expr
mp.ExitNodeID = unresolvedExitNodeID
}
} else {
mp.ExitNodeIDSet = true
mp.ExitNodeID = ""
mp.AutoExitNodeSet = true
mp.AutoExitNode = ""
mp.InternalExitNodePriorSet = true
if p0.AutoExitNode().IsSet() {
mp.InternalExitNodePrior = tailcfg.StableNodeID(ipn.AutoExitNodePrefix + p0.AutoExitNode())
} else {
mp.InternalExitNodePrior = p0.ExitNodeID()
}
}
return b.editPrefsLocked(actor, mp)
}
// MaybeClearAppConnector clears the routes from any AppConnector if
// AdvertiseRoutes has been set in the MaskedPrefs.
func (b *LocalBackend) MaybeClearAppConnector(mp *ipn.MaskedPrefs) error {
if !buildfeatures.HasAppConnectors {
return nil
}
var err error
if ac := b.AppConnector(); ac != nil && mp.AdvertiseRoutesSet {
err = ac.ClearRoutes()
if err != nil {
b.logf("appc: clear routes error: %v", err)
}
}
return err
}
// EditPrefs applies the changes in mp to the current prefs,
// acting as the tailscaled itself rather than a specific user.
func (b *LocalBackend) EditPrefs(mp *ipn.MaskedPrefs) (ipn.PrefsView, error) {
return b.EditPrefsAs(mp, ipnauth.Self)
}
// EditPrefsAs is like EditPrefs, but makes the change as the specified actor.
// It returns an error if the actor is not allowed to make the change.
func (b *LocalBackend) EditPrefsAs(mp *ipn.MaskedPrefs, actor ipnauth.Actor) (ipn.PrefsView, error) {
if mp.SetsInternal() {
return ipn.PrefsView{}, errors.New("can't set Internal fields")
}
b.mu.Lock()
defer b.mu.Unlock()
return b.editPrefsLocked(actor, mp)
}
// checkEditPrefsAccessLocked checks whether the current user has access
// to apply the changes in mp to the given prefs.
//
// It returns an error if the user is not allowed, or nil otherwise.
//
// b.mu must be held.
func (b *LocalBackend) checkEditPrefsAccessLocked(actor ipnauth.Actor, prefs ipn.PrefsView, mp *ipn.MaskedPrefs) error {
syncs.RequiresMutex(&b.mu)
var errs []error
if mp.RunSSHSet && mp.RunSSH && !envknob.CanSSHD() {
errs = append(errs, errors.New("Tailscale SSH server administratively disabled"))
}
// Check if the user is allowed to disconnect Tailscale.
if mp.WantRunningSet && !mp.WantRunning && b.pm.CurrentPrefs().WantRunning() {
if err := actor.CheckProfileAccess(b.pm.CurrentProfile(), ipnauth.Disconnect, b.extHost.AuditLogger()); err != nil {
errs = append(errs, err)
}
}
// Prevent users from changing exit node preferences
// when exit node usage is managed by policy.
if mp.ExitNodeIDSet || mp.ExitNodeIPSet || mp.AutoExitNodeSet {
isManaged, err := b.polc.HasAnyOf(pkey.ExitNodeID, pkey.ExitNodeIP)
if err != nil {
err = fmt.Errorf("policy check failed: %w", err)
} else if isManaged {
// Allow users to override ExitNode policy settings and select an exit node manually
// if permitted by [pkey.AllowExitNodeOverride].
//
// Disabling exit node usage entirely is not allowed.
allowExitNodeOverride, _ := b.polc.GetBoolean(pkey.AllowExitNodeOverride, false)
if !allowExitNodeOverride || b.changeDisablesExitNodeLocked(prefs, mp) {
err = errManagedByPolicy
}
}
if err != nil {
errs = append(errs, fmt.Errorf("exit node cannot be changed: %w", err))
}
}
return errors.Join(errs...)
}
// changeDisablesExitNodeLocked reports whether applying the change
// to the given prefs would disable exit node usage.
//
// In other words, it returns true if prefs.ExitNodeID is non-empty
// initially, but would become empty after applying the given change.
//
// It applies the same adjustments and resolves the exit node in the prefs
// as done during actual edits. While not optimal performance-wise,
// changing the exit node via LocalAPI isn't a hot path, and reusing
// the same logic ensures consistency and simplifies maintenance.
//
// b.mu must be held.
func (b *LocalBackend) changeDisablesExitNodeLocked(prefs ipn.PrefsView, change *ipn.MaskedPrefs) bool {
syncs.RequiresMutex(&b.mu)
if !buildfeatures.HasUseExitNode {
return false
}
if !change.AutoExitNodeSet && !change.ExitNodeIDSet && !change.ExitNodeIPSet {
// The change does not affect exit node usage.
return false
}
if prefs.ExitNodeID() == "" {
// Exit node usage is already disabled.
// Note that we do not check for ExitNodeIP here.
// If ExitNodeIP hasn't been resolved to a node,
// it's not enabled yet.
return false
}
// First, apply the adjustments to a copy of the changes,
// e.g., clear AutoExitNode if ExitNodeID is set.
tmpChange := new(*change)
tmpChange.Prefs = *change.Prefs.Clone()
b.adjustEditPrefsLocked(prefs, tmpChange)
// Then apply the adjusted changes to a copy of the current prefs,
// and resolve the exit node in the prefs.
tmpPrefs := prefs.AsStruct()
tmpPrefs.ApplyEdits(tmpChange)
b.resolveExitNodeInPrefsLocked(tmpPrefs)
// If ExitNodeID is empty after applying the changes,
// but wasn't empty before, then the change disables
// exit node usage.
return tmpPrefs.ExitNodeID == ""
}
// adjustEditPrefsLocked applies additional changes to mp if necessary,
// such as zeroing out mutually exclusive fields.
//
// It must not assume that the changes in mp will actually be applied.
//
// b.mu must be held.
func (b *LocalBackend) adjustEditPrefsLocked(prefs ipn.PrefsView, mp *ipn.MaskedPrefs) {
syncs.RequiresMutex(&b.mu)
// Zeroing the ExitNodeID via localAPI must also zero the prior exit node.
if mp.ExitNodeIDSet && mp.ExitNodeID == "" && !mp.InternalExitNodePriorSet {
mp.InternalExitNodePrior = ""
mp.InternalExitNodePriorSet = true
}
// Clear ExitNodeID if AutoExitNode is disabled and ExitNodeID is still unresolved.
if mp.AutoExitNodeSet && mp.AutoExitNode == "" && prefs.ExitNodeID() == unresolvedExitNodeID {
mp.ExitNodeIDSet = true
mp.ExitNodeID = ""
}
// Disable automatic exit node selection if the user explicitly sets
// ExitNodeID or ExitNodeIP.
if (mp.ExitNodeIDSet || mp.ExitNodeIPSet) && !mp.AutoExitNodeSet {
mp.AutoExitNodeSet = true
mp.AutoExitNode = ""
}
}
// onEditPrefsLocked is called when prefs are edited (typically, via LocalAPI),
// just before the changes in newPrefs are set for the current profile.
//
// The changes in mp have been allowed, but the resulting [ipn.Prefs]
// have not yet been applied and may be subject to reconciliation
// by [LocalBackend.reconcilePrefsLocked], either before or after being set.
//
// This method handles preference edits, typically initiated by the user,
// as opposed to reconfiguring the backend when the final prefs are set.
//
// b.mu must be held; mp must not be mutated by this method.
func (b *LocalBackend) onEditPrefsLocked(_ ipnauth.Actor, mp *ipn.MaskedPrefs, oldPrefs, newPrefs ipn.PrefsView) {
if mp.WantRunningSet && !mp.WantRunning && oldPrefs.WantRunning() {
// If a user has enough rights to disconnect, such as when [pkey.AlwaysOn]
// is disabled, or [pkey.AlwaysOnOverrideWithReason] is also set and the user
// provides a reason for disconnecting, then we should not force the "always on"
// mode on them until the policy changes, they switch to a different profile, etc.
b.overrideAlwaysOn = true
if reconnectAfter, _ := b.polc.GetDuration(pkey.ReconnectAfter, 0); reconnectAfter > 0 {
b.startReconnectTimerLocked(reconnectAfter)
}
}
if oldPrefs.WantRunning() != newPrefs.WantRunning() {
// Connecting to or disconnecting from Tailscale clears the override,
// unless the user is also explicitly changing the exit node (see below).
b.overrideExitNodePolicy = false
}
if mp.AutoExitNodeSet || mp.ExitNodeIDSet || mp.ExitNodeIPSet {
if allowExitNodeOverride, _ := b.polc.GetBoolean(pkey.AllowExitNodeOverride, false); allowExitNodeOverride {
// If applying exit node policy settings to the new prefs results in no change,
// the user is not overriding the policy. Otherwise, it is an override.
b.overrideExitNodePolicy = b.applyExitNodeSysPolicyLocked(newPrefs.AsStruct())
} else {
// Overrides are not allowed; clear the override flag.
b.overrideExitNodePolicy = false
}
}
if mp.AdvertiseServicesSet {
if ns, ok := b.sys.Netstack.GetOK(); ok {
ns.UpdateActiveVIPServices(newPrefs.AdvertiseServices())
}
}
// This is recorded here in the EditPrefs path, not the setPrefs path on purpose.
// recordForEdit records metrics related to edits and changes, not the final state.
// If, in the future, we want to record gauge-metrics related to the state of prefs,
// that should be done in the setPrefs path.
e := prefsMetricsEditEvent{
change: mp,
pNew: newPrefs,
pOld: oldPrefs,
node: b.currentNode(),
lastSuggestedExitNode: b.lastSuggestedExitNode,
}
e.record()
}
// startReconnectTimerLocked sets a timer to automatically set WantRunning to true
// after the specified duration.
func (b *LocalBackend) startReconnectTimerLocked(d time.Duration) {
syncs.RequiresMutex(&b.mu)
if b.reconnectTimer != nil {
// Stop may return false if the timer has already fired,
// and the function has been called in its own goroutine,
// but lost the race to acquire b.mu. In this case, it'll
// end up as a no-op due to a reconnectTimer mismatch
// once it manages to acquire the lock. This is fine, and we
// don't need to check the return value.
b.reconnectTimer.Stop()
}
profileID := b.pm.CurrentProfile().ID()
var reconnectTimer tstime.TimerController
reconnectTimer = b.clock.AfterFunc(d, func() {
b.mu.Lock()
defer b.mu.Unlock()
if b.reconnectTimer != reconnectTimer {
// We're either not the most recent timer, or we lost the race when
// the timer was stopped. No need to reconnect.
return
}
b.reconnectTimer = nil
cp := b.pm.CurrentProfile()
if cp.ID() != profileID {
// The timer fired before the profile changed but we lost the race
// and acquired the lock shortly after.
// No need to reconnect.
return
}
mp := &ipn.MaskedPrefs{WantRunningSet: true, Prefs: ipn.Prefs{WantRunning: true}}
if _, err := b.editPrefsLocked(ipnauth.Self, mp); err != nil {
b.logf("failed to automatically reconnect as %q after %v: %v", cp.Name(), d, err)
} else {
b.logf("automatically reconnected as %q after %v", cp.Name(), d)
}
})
b.reconnectTimer = reconnectTimer
b.logf("reconnect for %q has been scheduled and will be performed in %v", b.pm.CurrentProfile().Name(), d)
}
func (b *LocalBackend) resetAlwaysOnOverrideLocked() {
syncs.RequiresMutex(&b.mu)
b.overrideAlwaysOn = false
b.stopReconnectTimerLocked()
}
func (b *LocalBackend) stopReconnectTimerLocked() {
syncs.RequiresMutex(&b.mu)
if b.reconnectTimer != nil {
// Stop may return false if the timer has already fired,
// and the function has been called in its own goroutine,
// but lost the race to acquire b.mu.
// In this case, it'll end up as a no-op due to a reconnectTimer
// mismatch (see [LocalBackend.startReconnectTimerLocked])
// once it manages to acquire the lock. This is fine, and we
// don't need to check the return value.
b.reconnectTimer.Stop()
b.reconnectTimer = nil
}
}
// b.mu must be held.
func (b *LocalBackend) editPrefsLocked(actor ipnauth.Actor, mp *ipn.MaskedPrefs) (ipn.PrefsView, error) {
syncs.RequiresMutex(&b.mu)
p0 := b.pm.CurrentPrefs()
// Check if the changes in mp are allowed.
if err := b.checkEditPrefsAccessLocked(actor, p0, mp); err != nil {
b.logf("EditPrefs(%v): %v", mp.Pretty(), err)
return ipn.PrefsView{}, err
}
// Apply additional changes to mp if necessary,
// such as clearing mutually exclusive fields.
b.adjustEditPrefsLocked(p0, mp)
if mp.EggSet {
mp.EggSet = false
b.egg = true
b.goTracker.Go(b.doSetHostinfoFilterServices)
}
p1 := b.pm.CurrentPrefs().AsStruct()
p1.ApplyEdits(mp)
if err := b.checkPrefsLocked(p1); err != nil {
b.logf("EditPrefs check error: %v", err)
return ipn.PrefsView{}, err
}
if p1.View().Equals(p0) {
return stripKeysFromPrefs(p0), nil
}
b.logf("EditPrefs: %v", mp.Pretty())
// Perform any actions required when prefs are edited (typically by a user),
// before the modified prefs are actually set for the current profile.
b.onEditPrefsLocked(actor, mp, p0, p1.View())
newPrefs := b.setPrefsLocked(p1)
// Note: don't perform any actions for the new prefs here. Not
// every prefs change goes through EditPrefs. Put your actions
// in setPrefsLocked instead.
// This should return the public prefs, not the private ones.
return stripKeysFromPrefs(newPrefs), nil
}
func (b *LocalBackend) checkProfileNameLocked(p *ipn.Prefs) error {
if p.ProfileName == "" {
// It is always okay to clear the profile name.
return nil
}
id := b.pm.ProfileIDForName(p.ProfileName)
if id == "" {
// No profile with that name exists. That's fine.
return nil
}
if id != b.pm.CurrentProfile().ID() {
// Name is already in use by another profile.
return fmt.Errorf("profile name %q already in use", p.ProfileName)
}
return nil
}
// setPrefsLocked requires b.mu be held to call it.
// newp ownership passes to this function.
// It returns a read-only copy of the new prefs.
func (b *LocalBackend) setPrefsLocked(newp *ipn.Prefs) ipn.PrefsView {
cn := b.currentNode()
netMap := cn.NetMap()
b.setAtomicValuesFromPrefsLocked(newp.View())
oldp := b.pm.CurrentPrefs()
if oldp.Valid() {
newp.Persist = oldp.Persist().AsStruct() // caller isn't allowed to override this
}
// Apply reconciliation to the prefs, such as policy overrides,
// exit node resolution, and so on. The call returns whether it updated
// newp, but everything in this function treats newp as completely new
// anyway, so its return value can be ignored here.
b.reconcilePrefsLocked(newp)
// We do this to avoid holding the lock while doing everything else.
oldHi := b.hostinfo
newHi := oldHi.Clone()
if newHi == nil {
newHi = new(tailcfg.Hostinfo)
}
b.applyPrefsToHostinfoLocked(newHi, newp.View())
b.hostinfo = newHi
hostInfoChanged := !oldHi.Equal(newHi)
cc := b.cc
b.updateFilterLocked(newp.View())
if buildfeatures.HasSSH && oldp.ShouldSSHBeRunning() && !newp.ShouldSSHBeRunning() {
if b.sshServer != nil {
b.goTracker.Go(b.sshServer.Shutdown)
b.sshServer = nil
}
}
if netMap != nil {
newProfile := profileFromView(netMap.UserProfiles[netMap.User()])
if newLoginName := newProfile.LoginName; newLoginName != "" {
if !oldp.Persist().Valid() {
b.logf("active login: %s", newLoginName)
} else {
oldLoginName := oldp.Persist().UserProfile().LoginName()
if oldLoginName != newLoginName {
b.logf("active login: %q (changed from %q)", newLoginName, oldLoginName)
}
newp.Persist.UserProfile = newProfile
}
}
}
prefs := newp.View()
np := cmp.Or(cn.NetworkProfile(), b.pm.CurrentProfile().NetworkProfile())
if err := b.pm.SetPrefs(prefs, np); err != nil {
b.logf("failed to save new controlclient state: %v", err)
} else if prefs.WantRunning() {
// Reset the always-on override if WantRunning is true in the new prefs,
// such as when the user toggles the Connected switch in the GUI
// or runs `tailscale up`.
b.resetAlwaysOnOverrideLocked()
}
b.pauseOrResumeControlClientLocked() // for prefs.Sync changes
b.updateWarnSync(prefs)
b.updateNoSNATExitNodeWarning(prefs)
if oldp.ShieldsUp() != newp.ShieldsUp || hostInfoChanged {
b.doSetHostinfoFilterServicesLocked()
}
if netMap != nil {
b.MagicConn().SetDERPMap(netMap.DERPMap)
}
if !oldp.WantRunning() && newp.WantRunning && cc != nil {
b.logf("transitioning to running; doing Login...")
cc.Login(controlclient.LoginDefault)
}
if oldp.WantRunning() != newp.WantRunning {
b.stateMachineLocked()
} else {
b.authReconfigLocked()
}
if newp.AutoUpdate.Check && !oldp.AutoUpdate().Check {
if cv := b.lastClientVersion; cv != nil {
b.sendLocked(ipn.Notify{ClientVersion: cv})
}
}
b.sendLocked(ipn.Notify{Prefs: &prefs})
return prefs
}
// GetPeerAPIPort returns the port number for the peerapi server
// running on the provided IP.
func (b *LocalBackend) GetPeerAPIPort(ip netip.Addr) (port uint16, ok bool) {
if !buildfeatures.HasPeerAPIServer {
return 0, false
}
portInt, ok := b.peerAPIPorts.Load()[ip]
return uint16(portInt), ok
}
// handlePeerAPIConn serves an already-accepted connection c.
//
// The remote parameter is the remote address.
// The local parameter is the local address (either a Tailscale IPv4
// or IPv6 IP and the peerapi port for that address).
//
// The connection will be closed by handlePeerAPIConn.
func (b *LocalBackend) handlePeerAPIConn(remote, local netip.AddrPort, c net.Conn) {
b.mu.Lock()
defer b.mu.Unlock()
for _, pln := range b.peerAPIListeners {
if pln.ip == local.Addr() {
go pln.ServeConn(remote, c)
return
}
}
b.logf("[unexpected] no peerAPI listener found for %v", local)
c.Close()
return
}
func (b *LocalBackend) isLocalIP(ip netip.Addr) bool {
nm := b.NetMap()
return nm != nil && views.SliceContains(nm.GetAddresses(), netip.PrefixFrom(ip, ip.BitLen()))
}
var (
magicDNSIP = tsaddr.TailscaleServiceIP()
magicDNSIPv6 = tsaddr.TailscaleServiceIPv6()
)
// Hook exclusively for serve.
var (
hookServeTCPHandlerForVIPService feature.Hook[func(b *LocalBackend, dst netip.AddrPort, src netip.AddrPort) (handler func(c net.Conn) error)]
hookTCPHandlerForServe feature.Hook[func(b *LocalBackend, dport uint16, srcAddr netip.AddrPort, f *funnelFlow) (handler func(net.Conn) error)]
hookServeUpdateServeTCPPortNetMapAddrListenersLocked feature.Hook[func(b *LocalBackend, ports []uint16)]
hookServeSetTCPPortsInterceptedFromNetmapAndPrefsLocked feature.Hook[func(b *LocalBackend, prefs ipn.PrefsView) (handlePorts []uint16)]
hookServeClearVIPServicesTCPPortsInterceptedLocked feature.Hook[func(*LocalBackend)]
)
func (b *LocalBackend) handleDriveConn(conn net.Conn) error {
fs, ok := b.sys.DriveForLocal.GetOK()
if !ok || !b.DriveAccessEnabled() {
conn.Close()
return nil
}
return fs.HandleConn(conn, conn.RemoteAddr())
}
func (b *LocalBackend) peerAPIServicesLocked() (ret []tailcfg.Service) {
for _, pln := range b.peerAPIListeners {
proto := tailcfg.PeerAPI4
if pln.ip.Is6() {
proto = tailcfg.PeerAPI6
}
ret = append(ret, tailcfg.Service{
Proto: proto,
Port: uint16(pln.port),
})
}
switch runtime.GOOS {
case "linux", "freebsd", "openbsd", "illumos", "solaris", "darwin", "windows", "android", "ios":
// These are the platforms currently supported by
// net/dns/resolver/tsdns.go:Resolver.HandleExitNodeDNSQuery.
ret = append(ret, tailcfg.Service{
Proto: tailcfg.PeerAPIDNS,
Port: 1, // version
})
}
return ret
}
// PortlistServices is an eventbus topic for the portlist extension
// to advertise the running services on the host.
type PortlistServices []tailcfg.Service
func (b *LocalBackend) setPortlistServices(sl []tailcfg.Service) {
if !buildfeatures.HasPortList { // redundant, but explicit for linker deadcode and humans
return
}
b.mu.Lock()
if b.hostinfo == nil {
b.hostinfo = new(tailcfg.Hostinfo)
}
b.hostinfo.Services = sl
b.mu.Unlock()
b.doSetHostinfoFilterServices()
}
// doSetHostinfoFilterServices calls SetHostinfo on the controlclient,
// possibly after mangling the given hostinfo.
//
// TODO(danderson): we shouldn't be mangling hostinfo here after
// painstakingly constructing it in twelvety other places.
func (b *LocalBackend) doSetHostinfoFilterServices() {
b.mu.Lock()
defer b.mu.Unlock()
b.doSetHostinfoFilterServicesLocked()
}
// b.mu must be held
func (b *LocalBackend) doSetHostinfoFilterServicesLocked() {
cc := b.cc
if cc == nil {
// Control client isn't up yet.
return
}
if b.hostinfo == nil {
b.logf("[unexpected] doSetHostinfoFilterServices with nil hostinfo")
return
}
hi := b.hostInfoWithServicesLocked()
cc.SetHostinfo(hi)
}
// hostInfoWithServicesLocked returns a shallow clone of b.hostinfo with
// services added.
//
// b.mu must be held.
func (b *LocalBackend) hostInfoWithServicesLocked() *tailcfg.Hostinfo {
peerAPIServices := b.peerAPIServicesLocked()
if b.egg {
peerAPIServices = append(peerAPIServices, tailcfg.Service{Proto: "egg", Port: 1})
}
// TODO(maisem,bradfitz): store hostinfo as a view, not as a mutable struct.
hi := *b.hostinfo // shallow copy
// Make a shallow copy of hostinfo so we can mutate
// at the Service field.
if f, ok := b.extHost.Hooks().ShouldUploadServices.GetOk(); !ok || !f() {
hi.Services = []tailcfg.Service{}
}
// Don't mutate hi.Service's underlying array. Append to
// the slice with no free capacity.
c := len(hi.Services)
hi.Services = append(hi.Services[:c:c], peerAPIServices...)
hi.PushDeviceToken = b.pushDeviceToken.Load()
// Compare the expected ports from peerAPIServices to the actual ports in hi.Services.
expectedPorts := extractPeerAPIPorts(peerAPIServices)
actualPorts := extractPeerAPIPorts(hi.Services)
if expectedPorts != actualPorts {
b.logf("Hostinfo peerAPI ports changed: expected %v, got %v", expectedPorts, actualPorts)
}
return &hi
}
type portPair struct {
v4, v6 uint16
}
func extractPeerAPIPorts(services []tailcfg.Service) portPair {
var p portPair
for _, s := range services {
switch s.Proto {
case "peerapi4":
p.v4 = s.Port
case "peerapi6":
p.v6 = s.Port
}
}
return p
}
// NetMap returns the latest cached network map received from
// controlclient, or nil if no network map was received yet.
func (b *LocalBackend) NetMap() *netmap.NetworkMap {
return b.currentNode().NetMap()
}
func (b *LocalBackend) isEngineBlocked() bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.blocked
}
// blockEngineUpdatesLocked sets b.blocked to block.
//
// Its indirect effect is to turn b.authReconfig() into a no-op if block is
// true.
//
// b.mu must be held.
func (b *LocalBackend) blockEngineUpdatesLocked(block bool) {
b.logf("blockEngineUpdates(%v)", block)
b.blocked = block
}
// reconfigAppConnectorLocked updates the app connector state based on the
// current network map and preferences.
// b.mu must be held.
func (b *LocalBackend) reconfigAppConnectorLocked(nm *netmap.NetworkMap, prefs ipn.PrefsView) {
if !buildfeatures.HasAppConnectors {
return
}
const appConnectorCapName = "tailscale.com/app-connectors"
defer func() {
if b.hostinfo != nil {
b.hostinfo.AppConnector.Set(b.appConnector != nil)
}
}()
// App connectors have been disabled.
if !prefs.AppConnector().Advertise {
b.appConnector.Close() // clean up a previous connector (safe on nil)
b.appConnector = nil
return
}
// We don't (yet) have an app connector configured, or the configured
// connector has a different route persistence setting.
shouldStoreRoutes := b.ControlKnobs().AppCStoreRoutes.Load()
if b.appConnector == nil || (shouldStoreRoutes != b.appConnector.ShouldStoreRoutes()) {
ri, err := b.readRouteInfoLocked()
if err != nil && err != ipn.ErrStateNotExist {
b.logf("Unsuccessful Read RouteInfo: %v", err)
}
b.appConnector.Close() // clean up a previous connector (safe on nil)
b.appConnector = appc.NewAppConnector(appc.Config{
Logf: b.logf,
EventBus: b.sys.Bus.Get(),
RouteInfo: ri,
HasStoredRoutes: shouldStoreRoutes,
})
}
if nm == nil {
return
}
attrs, err := tailcfg.UnmarshalNodeCapViewJSON[appctype.AppConnectorAttr](nm.SelfNode.CapMap(), appConnectorCapName)
if err != nil {
b.logf("[unexpected] error parsing app connector mapcap: %v", err)
return
}
// Geometric cost, assumes that the number of advertised tags is small
selfHasTag := func(attrTags []string) bool {
return nm.SelfNode.Tags().ContainsFunc(func(tag string) bool {
return slices.Contains(attrTags, tag)
})
}
var (
domains []string
routes []netip.Prefix
)
for _, attr := range attrs {
if slices.Contains(attr.Connectors, "*") || selfHasTag(attr.Connectors) {
domains = append(domains, attr.Domains...)
routes = append(routes, attr.Routes...)
}
}
slices.Sort(domains)
slices.SortFunc(routes, func(i, j netip.Prefix) int { return i.Addr().Compare(j.Addr()) })
domains = slices.Compact(domains)
routes = slices.Compact(routes)
b.appConnector.UpdateDomainsAndRoutes(domains, routes)
}
func (b *LocalBackend) readvertiseAppConnectorRoutes() {
// Note: we should never call b.appConnector methods while holding b.mu.
// This can lead to a deadlock, like
// https://github.com/tailscale/corp/issues/25965.
//
// Grab a copy of the field, since b.mu only guards access to the
// b.appConnector field itself.
appConnector := b.AppConnector()
if appConnector == nil {
return
}
domainRoutes := appConnector.DomainRoutes()
if domainRoutes == nil {
return
}
// Re-advertise the stored routes, in case stored state got out of
// sync with previously advertised routes in prefs.
var prefixes []netip.Prefix
for _, ips := range domainRoutes {
for _, ip := range ips {
prefixes = append(prefixes, netip.PrefixFrom(ip, ip.BitLen()))
}
}
// Note: AdvertiseRoute will trim routes that are already
// advertised, so if everything is already being advertised this is
// a noop.
if err := b.AdvertiseRoute(prefixes...); err != nil {
b.logf("error advertising stored app connector routes: %v", err)
}
}
// authReconfig pushes a new configuration into wgengine, if engine
// updates are not currently blocked, based on the cached netmap and
// user prefs. Callers may experience an early return with no work
// done if another goroutine is waiting for the mutex inside this method.
// If there is no other goroutine waiting, the calling goroutine will
// proceed to reconfiguration after acquiring the mutex.
// Reconfiguration may run asynchronously and may not complete
// before the call returns.
func (b *LocalBackend) authReconfig() {
// If there's already a pending auth reconfig from another
// goroutine, exit early. If not, this goroutine becomes the pending.
if b.existsPendingAuthReconfig.Swap(true) {
return
}
b.mu.Lock()
defer b.mu.Unlock()
// Allow another goroutine to become pending.
b.existsPendingAuthReconfig.Store(false)
b.authReconfigLocked()
}
// authReconfigLocked is the locked version of [LocalBackend.authReconfig].
//
// b.mu must be held.
func (b *LocalBackend) authReconfigLocked() {
if b.shutdownCalled {
b.logf("[v1] authReconfig: skipping because in shutdown")
return
}
if b.blocked {
b.logf("[v1] authReconfig: blocked, skipping.")
return
}
cn := b.currentNode()
nm := cn.NetMap()
if nm == nil {
b.logf("[v1] authReconfig: netmap not yet valid. Skipping.")
return
}
prefs := b.pm.CurrentPrefs()
hasPAC := b.interfaceState.HasPAC()
disableSubnetsIfPAC := cn.SelfHasCap(tailcfg.NodeAttrDisableSubnetsIfPAC)
dohURL, dohURLOK := cn.exitNodeCanProxyDNS(prefs.ExitNodeID())
dcfg := cn.dnsConfigForNetmap(prefs, b.keyExpired, version.OS())
// If the current node is an app connector, ensure the app connector machine is started
b.reconfigAppConnectorLocked(nm, prefs)
if !prefs.WantRunning() {
b.logf("[v1] authReconfig: skipping because !WantRunning.")
return
}
var flags netmap.WGConfigFlags
if prefs.RouteAll() {
flags |= netmap.AllowSubnetRoutes
}
if hasPAC && disableSubnetsIfPAC {
if flags&netmap.AllowSubnetRoutes != 0 {
b.logf("authReconfig: have PAC; disabling subnet routes")
flags &^= netmap.AllowSubnetRoutes
}
}
// Keep the dialer updated about whether we're supposed to use
// an exit node's DNS server (so SOCKS5/HTTP outgoing dials
// can use it for name resolution)
if buildfeatures.HasUseExitNode {
if dohURLOK {
b.dialer.SetExitDNSDoH(dohURL)
} else {
b.dialer.SetExitDNSDoH("")
}
}
priv := b.pm.CurrentPrefs().Persist().PrivateNodeKey()
if !priv.IsZero() && priv.Public() != nm.NodeKey {
priv = key.NodePrivate{}
}
cfg, err := nmcfg.WGCfg(priv, nm, b.logf, flags, prefs.ExitNodeID())
if err != nil {
b.logf("wgcfg: %v", err)
return
}
oneCGNATRoute := shouldUseOneCGNATRoute(b.logf, b.sys.NetMon.Get(), b.sys.ControlKnobs(), version.OS())
rcfg := b.routerConfigLocked(cfg, prefs, nm, oneCGNATRoute)
// Add these extra Allowed IPs after router configuration, because the expected
// extension (features/conn25), does not want these routes installed on the OS.
// See also [Hooks.ExtraWireGuardAllowedIPs].
if extraAllowedIPsFn, ok := b.extHost.hooks.ExtraWireGuardAllowedIPs.GetOk(); ok {
for i := range cfg.Peers {
extras := extraAllowedIPsFn(cfg.Peers[i].PublicKey)
cfg.Peers[i].AllowedIPs = extras.AppendTo(cfg.Peers[i].AllowedIPs)
}
}
err = b.e.Reconfig(cfg, rcfg, dcfg)
if err == wgengine.ErrNoChanges {
return
}
b.logf("[v1] authReconfig: ra=%v dns=%v 0x%02x: %v", prefs.RouteAll(), prefs.CorpDNS(), flags, err)
b.initPeerAPIListenerLocked()
if buildfeatures.HasAppConnectors {
go b.goTracker.Go(b.readvertiseAppConnectorRoutes)
}
}
// shouldUseOneCGNATRoute reports whether we should prefer to make one big
// CGNAT /10 route rather than a /32 per peer.
//
// The versionOS is a Tailscale-style version ("iOS", "macOS") and not
// a runtime.GOOS.
func shouldUseOneCGNATRoute(logf logger.Logf, mon *netmon.Monitor, controlKnobs *controlknobs.Knobs, versionOS string) bool {
if controlKnobs != nil {
// Explicit enabling or disabling always take precedence.
if v, ok := controlKnobs.OneCGNAT.Load().Get(); ok {
logf("[v1] shouldUseOneCGNATRoute: explicit=%v", v)
return v
}
}
if versionOS == "plan9" {
// Just temporarily during plan9 bringup to have fewer routes to debug.
return true
}
// Also prefer to do this on the Mac, so that we don't need to constantly
// update the network extension configuration (which is disruptive to
// Chrome, see https://github.com/tailscale/tailscale/issues/3102). Only
// use fine-grained routes if another interfaces is also using the CGNAT
// IP range.
if versionOS == "macOS" {
hasCGNATInterface, err := mon.HasCGNATInterface()
if err != nil {
logf("shouldUseOneCGNATRoute: Could not determine if any interfaces use CGNAT: %v", err)
return false
}
logf("[v1] shouldUseOneCGNATRoute: macOS automatic=%v", !hasCGNATInterface)
if !hasCGNATInterface {
return true
}
}
return false
}
// SetTCPHandlerForFunnelFlow sets the TCP handler for Funnel flows.
// It should only be called before the LocalBackend is used.
func (b *LocalBackend) SetTCPHandlerForFunnelFlow(h func(src netip.AddrPort, dstPort uint16) (handler func(net.Conn))) {
b.getTCPHandlerForFunnelFlow = h
}
// SetVarRoot sets the root directory of Tailscale's writable
// storage area . (e.g. "/var/lib/tailscale")
//
// It should only be called before the LocalBackend is used.
func (b *LocalBackend) SetVarRoot(dir string) {
b.varRoot = dir
}
// SetLogFlusher sets a func to be called to flush log uploads.
//
// It should only be called before the LocalBackend is used.
func (b *LocalBackend) SetLogFlusher(flushFunc func()) {
if !buildfeatures.HasLogTail {
return
}
b.logFlushFunc = flushFunc
}
// TryFlushLogs calls the log flush function. It returns false if a log flush
// function was never initialized with SetLogFlusher.
//
// TryFlushLogs should not block.
func (b *LocalBackend) TryFlushLogs() bool {
if !buildfeatures.HasLogTail || b.logFlushFunc == nil {
return false
}
b.logFlushFunc()
return true
}
// TailscaleVarRoot returns the root directory of Tailscale's writable
// storage area. (e.g. "/var/lib/tailscale")
//
// It returns an empty string if there's no configured or discovered
// location.
func (b *LocalBackend) TailscaleVarRoot() string {
if b.varRoot != "" {
return b.varRoot
}
switch runtime.GOOS {
case "ios", "android", "darwin":
return paths.AppSharedDir.Load()
case "linux":
if distro.Get() == distro.Gokrazy {
return "/perm/tailscaled"
}
}
return ""
}
// ProfileMkdirAll creates (if necessary) and returns the path of a directory
// specific to the specified login profile, inside Tailscale's writable storage
// area. If subs are provided, they are joined to the base path to form the
// subdirectory path.
//
// It reports [ErrProfileStorageUnavailable] if there's no configured or
// discovered storage location, or if there was an error making the
// subdirectory.
func (b *LocalBackend) ProfileMkdirAll(id ipn.ProfileID, subs ...string) (string, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.profileMkdirAllLocked(id, subs...)
}
// profileDataPathLocked returns a path of a profile-specific (sub)directory
// inside the writable storage area for the given profile ID. It does not
// create or verify the existence of the path in the filesystem.
// If b.varRoot == "", it returns "". It panics if id is empty.
//
// The caller must hold b.mu.
func (b *LocalBackend) profileDataPathLocked(id ipn.ProfileID, subs ...string) string {
if id == "" {
panic("invalid empty profile ID")
}
vr := b.TailscaleVarRoot()
if vr == "" {
return ""
}
return filepath.Join(append([]string{vr, "profile-data", string(id)}, subs...)...)
}
// profileMkdirAllLocked implements ProfileMkdirAll.
// The caller must hold b.mu.
func (b *LocalBackend) profileMkdirAllLocked(id ipn.ProfileID, subs ...string) (string, error) {
if id == "" {
return "", errProfileNotFound
}
if vr := b.TailscaleVarRoot(); vr == "" {
return "", ErrProfileStorageUnavailable
}
// Use the LoginProfile ID rather than the UserProfile ID, as the latter may
// change over time.
dir := b.profileDataPathLocked(id, subs...)
if err := os.MkdirAll(dir, 0700); err != nil {
return "", fmt.Errorf("create profile directory: %w", err)
}
return dir, nil
}
// closePeerAPIListenersLocked closes any existing PeerAPI listeners
// and clears out the PeerAPI server state.
//
// It does not kick off any Hostinfo update with new services.
//
// b.mu must be held.
func (b *LocalBackend) closePeerAPIListenersLocked() {
if !buildfeatures.HasPeerAPIServer {
return
}
b.peerAPIServer = nil
for _, pln := range b.peerAPIListeners {
pln.Close()
}
b.peerAPIListeners = nil
b.peerAPIPorts.Store(nil)
}
// peerAPIListenAsync is whether the operating system requires that we
// retry listening on the peerAPI ip/port for whatever reason.
//
// On Windows, see Issue 1620.
// On Android, see Issue 1960.
const peerAPIListenAsync = runtime.GOOS == "windows" || runtime.GOOS == "android"
func (b *LocalBackend) initPeerAPIListener() {
b.mu.Lock()
defer b.mu.Unlock()
b.initPeerAPIListenerLocked()
}
// b.mu must be held.
func (b *LocalBackend) initPeerAPIListenerLocked() {
if !buildfeatures.HasPeerAPIServer {
return
}
b.logf("[v1] initPeerAPIListener: entered")
if b.shutdownCalled {
b.logf("[v1] initPeerAPIListener: shutting down")
return
}
cn := b.currentNode()
nm := cn.NetMap()
if nm == nil {
// We're called from authReconfigLocked which checks that
// netMap is non-nil, but if a concurrent Logout,
// ResetForClientDisconnect, or Start happens when its
// mutex was released, the netMap could be
// nil'ed out (Issue 1996). Bail out early here if so.
b.logf("[v1] initPeerAPIListener: no netmap")
return
}
addrs := nm.GetAddresses()
if addrs.Len() == len(b.peerAPIListeners) {
allSame := true
for i, pln := range b.peerAPIListeners {
if pln.ip != addrs.At(i).Addr() {
allSame = false
break
}
}
if allSame {
// Nothing to do.
b.logf("[v1] initPeerAPIListener: %d netmap addresses match existing listeners", addrs.Len())
// TODO(zofrex): This is fragile. It doesn't check what's actually in hostinfo, and if
// peerAPIListeners gets out of sync with hostinfo.Services, we won't get back into a good
// state. E.G. see tailscale/corp#27173.
return
}
}
b.closePeerAPIListenersLocked()
selfNode := nm.SelfNode
if !selfNode.Valid() || nm.GetAddresses().Len() == 0 {
b.logf("[v1] initPeerAPIListener: no addresses in netmap")
return
}
ps := &peerAPIServer{
b: b,
}
if dm, ok := b.sys.DNSManager.GetOK(); ok {
ps.resolver = dm.Resolver()
}
b.peerAPIServer = ps
isNetstack := b.sys.IsNetstack()
peerAPIPorts := make(map[netip.Addr]int)
for i, a := range addrs.All() {
var ln net.Listener
var err error
skipListen := i > 0 && isNetstack
if !skipListen {
// We don't care about the error here. Not all platforms set this.
// If ps.listen needs it, it will check for zero values and error out.
tsIfIndex, _ := netmon.TailscaleInterfaceIndex()
ln, err = ps.listen(a.Addr(), tsIfIndex)
if err != nil {
if peerAPIListenAsync {
b.logf("[v1] possibly transient peerapi listen(%q) error, will try again on linkChange: %v", a.Addr(), err)
// Expected. But we fix it later in linkChange
// ("peerAPIListeners too low").
continue
}
// Sandboxed macOS specifically requires the interface index to be non-zero.
if version.IsSandboxedMacOS() && tsIfIndex == 0 {
b.logf("[v1] peerapi listen(%q) error: interface index is 0 on darwin; try restarting tailscaled", a.Addr())
continue
}
b.logf("[unexpected] peerapi listen(%q) error: %v", a.Addr(), err)
continue
}
}
pln := &peerAPIListener{
ps: ps,
ip: a.Addr(),
ln: ln, // nil for 2nd+ on netstack
lb: b,
}
if skipListen {
pln.port = b.peerAPIListeners[0].port
} else {
pln.port = ln.Addr().(*net.TCPAddr).Port
}
pln.urlStr = "http://" + net.JoinHostPort(a.Addr().String(), strconv.Itoa(pln.port))
b.logf("peerapi: serving on %s", pln.urlStr)
go pln.serve()
b.peerAPIListeners = append(b.peerAPIListeners, pln)
peerAPIPorts[a.Addr()] = pln.port
}
b.peerAPIPorts.Store(peerAPIPorts)
b.goTracker.Go(b.doSetHostinfoFilterServices)
}
// magicDNSRootDomains returns the subset of nm.DNS.Domains that are the search domains for MagicDNS.
func magicDNSRootDomains(nm *netmap.NetworkMap) []dnsname.FQDN {
if v := nm.MagicDNSSuffix(); v != "" {
fqdn, err := dnsname.ToFQDN(v)
if err != nil {
// TODO: propagate error
return nil
}
ret := []dnsname.FQDN{
fqdn,
dnsname.FQDN("0.e.1.a.c.5.1.1.a.7.d.f.ip6.arpa."),
}
for i := 64; i <= 127; i++ {
fqdn, err = dnsname.ToFQDN(fmt.Sprintf("%d.100.in-addr.arpa.", i))
if err != nil {
// TODO: propagate error
continue
}
ret = append(ret, fqdn)
}
return ret
}
return nil
}
// peerRoutes returns the routerConfig.Routes to access peers.
// If there are over cgnatThreshold CGNAT routes, one big CGNAT route
// is used instead.
func peerRoutes(logf logger.Logf, peers []wgcfg.Peer, cgnatThreshold int, routeAll bool) (routes []netip.Prefix) {
tsULA := tsaddr.TailscaleULARange()
cgNAT := tsaddr.CGNATRange()
var didULA bool
var cgNATIPs []netip.Prefix
for _, peer := range peers {
for _, aip := range peer.AllowedIPs {
aip = unmapIPPrefix(aip)
// Ensure that we're only accepting properly-masked
// prefixes; the control server should be masking
// these, so if we get them, skip.
if mm := aip.Masked(); aip != mm {
// To avoid a DoS where a peer could cause all
// reconfigs to fail by sending a bad prefix, we just
// skip, but don't error, on an unmasked route.
logf("advertised route %s from %s has non-address bits set; expected %s", aip, peer.PublicKey.ShortString(), mm)
continue
}
// Only add the Tailscale IPv6 ULA once, if we see anybody using part of it.
if aip.Addr().Is6() && aip.IsSingleIP() && tsULA.Contains(aip.Addr()) {
if !didULA {
didULA = true
routes = append(routes, tsULA)
}
continue
}
if aip.IsSingleIP() && cgNAT.Contains(aip.Addr()) {
cgNATIPs = append(cgNATIPs, aip)
} else if routeAll {
routes = append(routes, aip)
}
}
}
if len(cgNATIPs) > cgnatThreshold {
// Probably the hello server. Just append one big route.
routes = append(routes, cgNAT)
} else {
routes = append(routes, cgNATIPs...)
}
tsaddr.SortPrefixes(routes)
return routes
}
// routerConfig produces a router.Config from a wireguard config and IPN prefs.
//
// b.mu must be held.
func (b *LocalBackend) routerConfigLocked(cfg *wgcfg.Config, prefs ipn.PrefsView, nm *netmap.NetworkMap, oneCGNATRoute bool) *router.Config {
singleRouteThreshold := 10_000
if oneCGNATRoute {
singleRouteThreshold = 1
}
netfilterKind := b.capForcedNetfilter // protected by b.mu (hence the Locked suffix)
if prefs.NetfilterKind() != "" {
if netfilterKind != "" {
b.logf("nodeattr netfilter preference %s overridden by c2n pref %s", netfilterKind, prefs.NetfilterKind())
}
netfilterKind = prefs.NetfilterKind()
}
var doStatefulFiltering bool
if v, ok := prefs.NoStatefulFiltering().Get(); ok && !v {
// The preferences explicitly "do stateful filtering" is turned
// off, or to expand the double negative, to do stateful
// filtering. Do so.
doStatefulFiltering = true
}
rs := &router.Config{
LocalAddrs: unmapIPPrefixes(cfg.Addresses),
SubnetRoutes: unmapIPPrefixes(prefs.AdvertiseRoutes().AsSlice()),
SNATSubnetRoutes: !prefs.NoSNAT(),
StatefulFiltering: doStatefulFiltering,
NetfilterMode: prefs.NetfilterMode(),
Routes: peerRoutes(b.logf, cfg.Peers, singleRouteThreshold, prefs.RouteAll()),
NetfilterKind: netfilterKind,
RemoveCGNATDropRule: nm.HasCap(tailcfg.NodeAttrDisableLinuxCGNATDropRule),
}
if buildfeatures.HasSynology && distro.Get() == distro.Synology {
// Issue 1995: we don't use iptables on Synology.
rs.NetfilterMode = preftype.NetfilterOff
}
// Sanity check: we expect the control server to program both a v4
// and a v6 default route, if default routing is on. Fill in
// blackhole routes appropriately if we're missing some. This is
// likely to break some functionality, but if the user expressed a
// preference for routing remotely, we want to avoid leaking
// traffic at the expense of functionality.
if buildfeatures.HasUseExitNode && (prefs.ExitNodeID() != "" || prefs.ExitNodeIP().IsValid()) {
var default4, default6 bool
for _, route := range rs.Routes {
switch route {
case tsaddr.AllIPv4():
default4 = true
case tsaddr.AllIPv6():
default6 = true
}
if default4 && default6 {
break
}
}
if !default4 {
rs.Routes = append(rs.Routes, tsaddr.AllIPv4())
}
if !default6 {
rs.Routes = append(rs.Routes, tsaddr.AllIPv6())
}
internalIPs, externalIPs, err := internalAndExternalInterfaces()
if err != nil {
b.logf("failed to discover interface ips: %v", err)
}
switch runtime.GOOS {
case "linux", "windows", "darwin", "ios", "android", "openbsd":
rs.LocalRoutes = internalIPs // unconditionally allow access to guest VM networks
if prefs.ExitNodeAllowLANAccess() {
rs.LocalRoutes = append(rs.LocalRoutes, externalIPs...)
} else {
// Explicitly add routes to the local network so that we do not
// leak any traffic.
rs.Routes = append(rs.Routes, externalIPs...)
}
b.logf("allowing exit node access to local IPs: %v", rs.LocalRoutes)
default:
if prefs.ExitNodeAllowLANAccess() {
b.logf("warning: ExitNodeAllowLANAccess has no effect on " + runtime.GOOS)
}
}
}
// Get the VIPs for VIP services this node hosts. We will add all locally served VIPs to routes then
// we terminate these connection locally in netstack instead of routing to peer.
vipServiceIPs := nm.GetIPVIPServiceMap()
v4, v6 := false, false
if slices.ContainsFunc(rs.LocalAddrs, tsaddr.PrefixIs4) {
rs.Routes = append(rs.Routes, netip.PrefixFrom(tsaddr.TailscaleServiceIP(), 32))
v4 = true
}
if slices.ContainsFunc(rs.LocalAddrs, tsaddr.PrefixIs6) {
rs.Routes = append(rs.Routes, netip.PrefixFrom(tsaddr.TailscaleServiceIPv6(), 128))
v6 = true
}
for vip := range vipServiceIPs {
if (vip.Is4() && v4) || (vip.Is6() && v6) {
rs.Routes = append(rs.Routes, netip.PrefixFrom(vip, vip.BitLen()))
}
}
// Get any extra Routes an extension may want installed.
if extensionRoutesFx, ok := b.extHost.hooks.ExtraRouterConfigRoutes.GetOk(); ok {
rs.Routes = extensionRoutesFx().AppendTo(rs.Routes)
}
return rs
}
func unmapIPPrefix(ipp netip.Prefix) netip.Prefix {
return netip.PrefixFrom(ipp.Addr().Unmap(), ipp.Bits())
}
func unmapIPPrefixes(ippsList ...[]netip.Prefix) (ret []netip.Prefix) {
for _, ipps := range ippsList {
for _, ipp := range ipps {
ret = append(ret, unmapIPPrefix(ipp))
}
}
return ret
}
// b.mu must be held.
func (b *LocalBackend) applyPrefsToHostinfoLocked(hi *tailcfg.Hostinfo, prefs ipn.PrefsView) {
if h := prefs.Hostname(); h != "" {
hi.Hostname = h
}
hi.RoutableIPs = prefs.AdvertiseRoutes().AsSlice()
hi.RequestTags = prefs.AdvertiseTags().AsSlice()
hi.ShieldsUp = prefs.ShieldsUp()
hi.AllowsUpdate = buildfeatures.HasClientUpdate && (envknob.AllowsRemoteUpdate() || prefs.AutoUpdate().Apply.EqualBool(true))
if buildfeatures.HasAdvertiseRoutes {
b.metrics.advertisedRoutes.Set(float64(tsaddr.WithoutExitRoute(prefs.AdvertiseRoutes()).Len()))
// Set up IP forwarding check when routes change
if len(hi.RoutableIPs) > 0 && b.NetMon() != nil && !b.sys.IsNetstackRouter() {
routes := hi.RoutableIPs
netMon := b.NetMon()
b.health.SetIPForwardingCheck(func() bool {
warn, err := netutil.CheckIPForwarding(routes, netMon.InterfaceState())
if err != nil {
metricIPForwardingCheckError.Add(1)
return false // don't want false positives
}
return warn != nil // true if broken
})
} else {
b.health.SetIPForwardingCheck(nil)
}
}
var sshHostKeys []string
if buildfeatures.HasSSH && prefs.RunSSH() && envknob.CanSSHD() {
// TODO(bradfitz): this is called with b.mu held. Not ideal.
// If the filesystem gets wedged or something we could block for
// a long time. But probably fine.
if f, ok := feature.HookGetSSHHostKeyPublicStrings.GetOk(); ok {
var err error
sshHostKeys, err = f(b.TailscaleVarRoot(), b.logf)
if err != nil {
b.logf("warning: unable to get SSH host keys, SSH will appear as disabled for this node: %v", err)
}
}
}
hi.SSH_HostKeys = sshHostKeys
if buildfeatures.HasRelayServer {
hi.PeerRelay = prefs.RelayServerPort().Valid()
}
for _, f := range hookMaybeMutateHostinfoLocked {
f(b, hi, prefs)
}
if buildfeatures.HasAppConnectors {
hi.AppConnector.Set(prefs.AppConnector().Advertise)
}
// The [tailcfg.Hostinfo.ExitNodeID] field tells control which exit node
// was selected, if any.
//
// If auto exit node is enabled (via [ipn.Prefs.AutoExitNode] or
// [pkey.ExitNodeID]), or an exit node is specified by ExitNodeIP
// instead of ExitNodeID , and we don't yet have enough info to resolve
// it (usually due to missing netmap or net report), then ExitNodeID in
// the prefs may be invalid (typically, [unresolvedExitNodeID]) until
// the netmap is available.
//
// In this case, we shouldn't update the Hostinfo with the bogus
// ExitNodeID here; [LocalBackend.ResolveExitNode] will be called once
// the netmap and/or net report have been received to both pick the exit
// node and notify control of the change.
if buildfeatures.HasUseExitNode {
if sid := prefs.ExitNodeID(); sid != unresolvedExitNodeID {
hi.ExitNodeID = prefs.ExitNodeID()
}
}
}
// enterStateLocked transitions the backend into newState, updating internal
// state and propagating events out as needed.
//
// TODO(danderson): while this isn't a lie, exactly, a ton of other
// places twiddle IPN internal state without going through here, so
// really this is more "one of several places in which random things
// happen".
//
// b.mu must be held.
func (b *LocalBackend) enterStateLocked(newState ipn.State) {
cn := b.currentNode()
oldState := b.state
b.setStateLocked(newState)
prefs := b.pm.CurrentPrefs()
// Some temporary (2024-05-05) debugging code to help us catch
// https://github.com/tailscale/tailscale/issues/11962 in the act.
if prefs.WantRunning() &&
prefs.ControlURLOrDefault(b.polc) == ipn.DefaultControlURL &&
envknob.Bool("TS_PANIC_IF_HIT_MAIN_CONTROL") {
panic("[unexpected] use of main control server in integration test")
}
netMap := cn.NetMap()
activeLogin := b.activeLogin
authURL := b.authURL
if newState == ipn.Running {
// TODO(zofrex): Is this needed? As of 2025-10-03 it doesn't seem to be
// necessary when logging in or authenticating. When do we need to reset it
// here, rather than the other places it is reset? We should test if it is
// necessary and add unit tests to cover those cases, or remove it.
if oldState != ipn.Running {
b.resetAuthURLLocked()
}
// Start a captive portal detection loop if none has been
// started. Create a new context if none is present, since it
// can be shut down if we transition away from Running.
if buildfeatures.HasCaptivePortal {
if b.captiveCancel == nil {
captiveCtx, captiveCancel := context.WithCancel(b.ctx)
b.captiveCtx, b.captiveCancel = captiveCtx, captiveCancel
b.goTracker.Go(func() { hookCheckCaptivePortalLoop.Get()(b, captiveCtx) })
}
}
} else if oldState == ipn.Running {
// Transitioning away from running.
b.closePeerAPIListenersLocked()
// Stop any existing captive portal detection loop.
if buildfeatures.HasCaptivePortal && b.captiveCancel != nil {
b.captiveCancel()
b.captiveCancel = nil
// NOTE: don't set captiveCtx to nil here, to ensure
// that we always have a (canceled) context to wait on
// in onHealthChange.
}
}
b.pauseOrResumeControlClientLocked()
// prefs may change irrespective of state; WantRunning should be explicitly
// set before potential early return even if the state is unchanged.
b.health.SetIPNState(newState.String(), prefs.Valid() && prefs.WantRunning())
if oldState == newState {
return
}
b.logf("Switching ipn state %v -> %v (WantRunning=%v, nm=%v)",
oldState, newState, prefs.WantRunning(), netMap != nil)
b.sendLocked(ipn.Notify{State: &newState})
switch newState {
case ipn.NeedsLogin:
feature.SystemdStatus("Needs login: %s", authURL)
// always block updates on NeedsLogin even if seamless renewal is enabled,
// to prevent calls to authReconfigLocked from reconfiguring the engine when our
// key has expired and we're waiting to authenticate to use the new key.
b.blockEngineUpdatesLocked(true)
fallthrough
case ipn.Stopped, ipn.NoState:
// Unconfigure the engine if it has stopped (WantRunning is set to false)
// or if we've switched to a different profile and the state is unknown.
err := b.e.Reconfig(&wgcfg.Config{}, &router.Config{}, &dns.Config{})
if err != nil {
b.logf("Reconfig(down): %v", err)
}
if newState == ipn.Stopped && authURL == "" {
feature.SystemdStatus("Stopped; run 'tailscale up' to log in")
}
case ipn.Starting, ipn.NeedsMachineAuth:
b.authReconfigLocked()
// Needed so that UpdateEndpoints can run
b.goTracker.Go(b.e.RequestStatus)
case ipn.Running:
if feature.CanSystemdStatus {
var addrStrs []string
addrs := netMap.GetAddresses()
for _, p := range addrs.All() {
addrStrs = append(addrStrs, p.Addr().String())
}
feature.SystemdStatus("Connected; %s; %s", activeLogin, strings.Join(addrStrs, " "))
}
default:
b.logf("[unexpected] unknown newState %#v", newState)
}
}
func (b *LocalBackend) hasNodeKeyLocked() bool {
syncs.RequiresMutex(&b.mu)
// we can't use b.Prefs(), because it strips the keys, oops!
p := b.pm.CurrentPrefs()
return p.Valid() && p.Persist().Valid() && !p.Persist().PrivateNodeKey().IsZero()
}
// NodeKey returns the public node key.
func (b *LocalBackend) NodeKey() key.NodePublic {
b.mu.Lock()
defer b.mu.Unlock()
if !b.hasNodeKeyLocked() {
return key.NodePublic{}
}
return b.pm.CurrentPrefs().Persist().PublicNodeKey()
}
// nextStateLocked returns the state the backend seems to be in, based on
// its internal state.
//
// b.mu must be held
func (b *LocalBackend) nextStateLocked() ipn.State {
syncs.RequiresMutex(&b.mu)
if b.health.IsUnhealthy(ipn.StateStoreHealth) {
return ipn.NoState
}
var (
cc = b.cc
cn = b.currentNode()
netMap = cn.NetMap()
state = b.state
blocked = b.blocked
st = b.engineStatus
keyExpired = b.keyExpired
wantRunning = false
loggedOut = false
)
if p := b.pm.CurrentPrefs(); p.Valid() {
wantRunning = p.WantRunning()
loggedOut = p.LoggedOut()
}
switch {
case !wantRunning && !loggedOut && !blocked && b.hasNodeKeyLocked():
return ipn.Stopped
case netMap == nil:
if (cc != nil && cc.AuthCantContinue()) || loggedOut {
// Auth was interrupted or waiting for URL visit,
// so it won't proceed without human help.
return ipn.NeedsLogin
}
switch state {
case ipn.Stopped:
// If we were already in the Stopped state, then
// we can assume auth is in good shape (or we would
// have been in NeedsLogin), so transition to Starting
// right away.
return ipn.Starting
case ipn.NoState:
// Our first time connecting to control, and we
// don't know if we'll NeedsLogin or not yet.
// UIs should print "Loading..." in this state.
return ipn.NoState
case ipn.Starting, ipn.Running, ipn.NeedsLogin:
return state
default:
b.logf("unexpected no-netmap state transition for %v", state)
return state
}
case !wantRunning:
return ipn.Stopped
case keyExpired:
// NetMap must be non-nil for us to get here.
// The node key expired, need to relogin.
return ipn.NeedsLogin
case netMap.GetMachineStatus() != tailcfg.MachineAuthorized:
// TODO(crawshaw): handle tailcfg.MachineInvalid
return ipn.NeedsMachineAuth
case state == ipn.NeedsMachineAuth:
// (if we get here, we know MachineAuthorized == true)
return ipn.Starting
case state == ipn.Starting:
if st.NumLive > 0 || st.LiveDERPs > 0 {
return ipn.Running
} else {
return state
}
case state == ipn.Running:
return ipn.Running
default:
return ipn.Starting
}
}
// stateMachine updates the state machine state based on other things
// that have happened. It is invoked from the various callbacks that
// feed events into LocalBackend.
//
// requires b.mu to be held.
func (b *LocalBackend) stateMachineLocked() {
syncs.RequiresMutex(&b.mu)
b.enterStateLocked(b.nextStateLocked())
}
// stopEngineAndWait deconfigures the local network data plane, and
// waits for it to deliver a status update indicating it has stopped
// before returning.
//
// b.mu must be held.
func (b *LocalBackend) stopEngineAndWaitLocked() {
syncs.RequiresMutex(&b.mu)
b.logf("stopEngineAndWait...")
st, err := b.e.ResetAndStop()
if err != nil {
// TODO(braditz): our caller, popBrowserAuthNowLocked, probably
// should handle this somehow. For now, just log it.
// See tailscale/tailscale#18187
b.logf("stopEngineAndWait: ResetAndStop error: %v", err)
return
}
b.setWgengineStatusLocked(st)
b.logf("stopEngineAndWait: done.")
}
// setControlClientLocked sets the control client to cc,
// which may be nil.
//
// b.mu must be held.
func (b *LocalBackend) setControlClientLocked(cc controlclient.Client) {
b.cc = cc
b.ccAuto, _ = cc.(*controlclient.Auto)
b.ignoreControlClientUpdates.Store(cc == nil)
}
// resetControlClientLocked sets b.cc to nil and returns the old value. If the
// returned value is non-nil, the caller must call Shutdown on it after
// releasing b.mu.
func (b *LocalBackend) resetControlClientLocked() controlclient.Client {
syncs.RequiresMutex(&b.mu)
if b.cc == nil {
return nil
}
b.resetAuthURLLocked()
// When we clear the control client, stop any outstanding netmap expiry
// timer; synthesizing a new netmap while we don't have a control
// client will break things.
//
// See https://github.com/tailscale/tailscale/issues/7392
if b.nmExpiryTimer != nil {
b.nmExpiryTimer.Stop()
b.nmExpiryTimer = nil
// Also bump the epoch to ensure that if the timer started, it
// will abort.
b.numClientStatusCalls.Add(1)
}
prev := b.cc
b.setControlClientLocked(nil)
return prev
}
// resetAuthURLLocked resets authURL, canceling any pending interactive login.
func (b *LocalBackend) resetAuthURLLocked() {
syncs.RequiresMutex(&b.mu)
b.authURL = ""
b.authURLTime = time.Time{}
b.authActor = nil
}
func (b *LocalBackend) ShouldRunSSH() bool { return b.sshAtomicBool.Load() && envknob.CanSSHD() }
// ShouldRunWebClient reports whether the web client is being run
// within this tailscaled instance. ShouldRunWebClient is safe to
// call regardless of whether b.mu is held or not.
func (b *LocalBackend) ShouldRunWebClient() bool { return b.webClientAtomicBool.Load() }
// ShouldExposeRemoteWebClient reports whether the web client should
// accept connections via [tailscale IP]:5252 in addition to the default
// behaviour of accepting local connections over 100.100.100.100.
//
// This function checks both the web client user pref via
// exposeRemoteWebClientAtomicBool and the disable-web-client node attr
// via ShouldRunWebClient to determine whether the web client should be
// exposed.
func (b *LocalBackend) ShouldExposeRemoteWebClient() bool {
return b.ShouldRunWebClient() && b.exposeRemoteWebClientAtomicBool.Load()
}
// setWebClientAtomicBoolLocked sets webClientAtomicBool based on whether
// tailcfg.NodeAttrDisableWebClient has been set in the netmap.NetworkMap.
//
// b.mu must be held.
func (b *LocalBackend) setWebClientAtomicBoolLocked(nm *netmap.NetworkMap) {
syncs.RequiresMutex(&b.mu)
shouldRun := !nm.HasCap(tailcfg.NodeAttrDisableWebClient)
wasRunning := b.webClientAtomicBool.Swap(shouldRun)
if wasRunning && !shouldRun {
b.goTracker.Go(b.webClientShutdown) // stop web client
}
}
// setExposeRemoteWebClientAtomicBoolLocked sets exposeRemoteWebClientAtomicBool
// based on whether the RunWebClient pref is set.
//
// b.mu must be held.
func (b *LocalBackend) setExposeRemoteWebClientAtomicBoolLocked(prefs ipn.PrefsView) {
syncs.RequiresMutex(&b.mu)
if !buildfeatures.HasWebClient {
return
}
shouldExpose := prefs.Valid() && prefs.RunWebClient()
b.exposeRemoteWebClientAtomicBool.Store(shouldExpose)
}
// ShouldHandleViaIP reports whether ip is an IPv6 address in the
// Tailscale ULA's v6 "via" range embedding an IPv4 address to be forwarded to
// by Tailscale.
func (b *LocalBackend) ShouldHandleViaIP(ip netip.Addr) bool {
if f, ok := b.containsViaIPFuncAtomic.LoadOk(); ok {
return f(ip)
}
return false
}
// Logout logs out the current profile, if any, and waits for the logout to
// complete.
func (b *LocalBackend) Logout(ctx context.Context, actor ipnauth.Actor) error {
b.mu.Lock()
if !b.hasNodeKeyLocked() {
// Already logged out.
b.mu.Unlock()
return nil
}
cc := b.cc
// Grab the current profile before we unlock the mutex, so that we can
// delete it later.
profile := b.pm.CurrentProfile()
_, err := b.editPrefsLocked(
actor,
&ipn.MaskedPrefs{
WantRunningSet: true,
LoggedOutSet: true,
Prefs: ipn.Prefs{WantRunning: false, LoggedOut: true},
})
b.mu.Unlock()
if err != nil {
return err
}
// Clear any previous dial plan(s), if set.
b.resetDialPlan()
if cc == nil {
// Double Logout can happen via repeated IPN
// connections to ipnserver making it repeatedly
// transition from 1->0 total connections, which on
// Windows by default ("client mode") causes a Logout
// on the transition to zero.
// Previously this crashed when we asserted that c was non-nil
// here.
return errors.New("no controlclient")
}
if err := cc.Logout(ctx); err != nil {
return err
}
b.mu.Lock()
defer b.mu.Unlock()
if err := b.pm.DeleteProfile(profile.ID()); err != nil {
b.logf("error deleting profile: %v", err)
return err
}
return b.resetForProfileChangeLocked()
}
// setNetInfo sets b.hostinfo.NetInfo to ni, and passes ni along to the
// controlclient, if one exists.
func (b *LocalBackend) setNetInfo(ni *tailcfg.NetInfo) {
b.mu.Lock()
cc := b.cc
var refresh bool
if b.MagicConn().DERPs() > 0 || testenv.InTest() {
// When b.refreshAutoExitNode is set, we recently observed a link change
// that indicates we have switched networks. After switching networks,
// the previously selected automatic exit node is no longer as likely
// to be a good choice and connectivity will already be broken due to
// the network switch. Therefore, it is a good time to switch to a new
// exit node because the network is already disrupted.
//
// Unfortunately, at the time of the link change, no information is
// known about the new network's latency or location, so the necessary
// details are not available to make a new choice. Instead, it sets
// b.refreshAutoExitNode to signal that a new decision should be made
// when we have an updated netcheck report. ni is that updated report.
//
// However, during testing we observed that often the first ni is
// inconclusive because it was running during the link change or the
// link was otherwise not stable yet. b.MagicConn().updateEndpoints()
// can detect when the netcheck failed and trigger a rebind, but the
// required information is not available here, and moderate additional
// plumbing is required to pass that in. Instead, checking for an active
// DERP link offers an easy approximation. We will continue to refine
// this over time.
refresh = b.refreshAutoExitNode
b.refreshAutoExitNode = false
}
b.mu.Unlock()
if cc == nil {
return
}
cc.SetNetInfo(ni)
if refresh {
b.RefreshExitNode()
}
}
// RefreshExitNode determines which exit node to use based on the current
// prefs and netmap and switches to it if needed.
func (b *LocalBackend) RefreshExitNode() {
if !buildfeatures.HasUseExitNode {
return
}
b.mu.Lock()
defer b.mu.Unlock()
b.refreshExitNodeLocked()
}
// refreshExitNodeLocked is like RefreshExitNode but requires b.mu be held.
func (b *LocalBackend) refreshExitNodeLocked() {
syncs.RequiresMutex(&b.mu)
if b.resolveExitNodeLocked() {
b.authReconfigLocked()
}
}
// resolveExitNodeLocked determines which exit node to use based on the current prefs
// and netmap. It updates the exit node ID in the prefs if needed, updates the
// exit node ID in the hostinfo if needed, sends a notification to clients, and
// returns true if the exit node has changed.
//
// It is the caller's responsibility to reconfigure routes and actually
// start using the selected exit node, if needed.
//
// b.mu must be held.
func (b *LocalBackend) resolveExitNodeLocked() (changed bool) {
syncs.RequiresMutex(&b.mu)
if !buildfeatures.HasUseExitNode {
return false
}
nm := b.currentNode().NetMap()
prefs := b.pm.CurrentPrefs().AsStruct()
if !b.resolveExitNodeInPrefsLocked(prefs) {
return
}
if err := b.pm.SetPrefs(prefs.View(), ipn.NetworkProfile{
MagicDNSName: nm.MagicDNSSuffix(),
DomainName: nm.DomainName(),
DisplayName: nm.TailnetDisplayName(),
}); err != nil {
b.logf("failed to save exit node changes: %v", err)
}
// Send the resolved exit node to control via [tailcfg.Hostinfo].
// [LocalBackend.applyPrefsToHostinfoLocked] usually sets the Hostinfo,
// but it deferred until this point because there was a bogus ExitNodeID
// in the prefs.
//
// TODO(sfllaw): Mutating b.hostinfo here is undesirable, mutating
// in-place doubly so.
sid := prefs.ExitNodeID
if sid != unresolvedExitNodeID && b.hostinfo.ExitNodeID != sid {
b.hostinfo.ExitNodeID = sid
b.goTracker.Go(b.doSetHostinfoFilterServices)
}
b.sendToLocked(ipn.Notify{Prefs: new(prefs.View())}, allClients)
return true
}
// reconcilePrefsLocked applies policy overrides, exit node resolution,
// and other post-processing to the prefs, and reports whether the prefs
// were modified as a result.
//
// It must not perform any reconfiguration, as the prefs are not yet effective.
//
// b.mu must be held.
func (b *LocalBackend) reconcilePrefsLocked(prefs *ipn.Prefs) (changed bool) {
if buildfeatures.HasSystemPolicy && b.applySysPolicyLocked(prefs) {
changed = true
}
if buildfeatures.HasUseExitNode && b.resolveExitNodeInPrefsLocked(prefs) {
changed = true
}
if changed {
b.logf("prefs reconciled: %v", prefs.Pretty())
}
return changed
}
// resolveExitNodeInPrefsLocked determines which exit node to use
// based on the specified prefs and netmap. It updates the exit node ID
// in the prefs if needed, and returns true if the exit node has changed.
//
// b.mu must be held.
func (b *LocalBackend) resolveExitNodeInPrefsLocked(prefs *ipn.Prefs) (changed bool) {
syncs.RequiresMutex(&b.mu)
if !buildfeatures.HasUseExitNode {
return false
}
if b.resolveAutoExitNodeLocked(prefs) {
changed = true
}
if b.resolveExitNodeIPLocked(prefs) {
changed = true
}
return changed
}
// setNetMapLocked updates the LocalBackend state to reflect the newly
// received nm. If nm is nil, it resets all configuration as though
// Tailscale is turned off.
func (b *LocalBackend) setNetMapLocked(nm *netmap.NetworkMap) {
oldSelf := b.currentNode().NetMap().SelfNodeOrZero()
b.dialer.SetNetMap(nm)
if ns, ok := b.sys.Netstack.GetOK(); ok {
ns.UpdateNetstackIPs(nm)
}
var login string
if nm != nil {
login = cmp.Or(profileFromView(nm.UserProfiles[nm.User()]).LoginName, "<missing-profile>")
}
b.currentNode().SetNetMap(nm)
if ms, ok := b.sys.MagicSock.GetOK(); ok {
if nm != nil {
ms.SetNetworkMap(nm.SelfNode, nm.Peers)
} else {
ms.SetNetworkMap(tailcfg.NodeView{}, nil)
}
}
if login != b.activeLogin {
b.logf("active login: %v", login)
b.activeLogin = login
}
b.pauseOrResumeControlClientLocked()
if nm != nil {
messages := make(map[tailcfg.DisplayMessageID]tailcfg.DisplayMessage)
for id, msg := range nm.DisplayMessages {
if msg.PrimaryAction != nil && !b.validPopBrowserURLLocked(msg.PrimaryAction.URL) {
msg.PrimaryAction = nil
}
messages[id] = msg
}
b.health.SetControlHealth(messages)
} else {
b.health.SetControlHealth(nil)
}
if runtime.GOOS == "linux" && buildfeatures.HasOSRouter {
if nm.HasCap(tailcfg.NodeAttrLinuxMustUseIPTables) {
b.capForcedNetfilter = "iptables"
} else if nm.HasCap(tailcfg.NodeAttrLinuxMustUseNfTables) {
b.capForcedNetfilter = "nftables"
} else {
b.capForcedNetfilter = "" // empty string means client can auto-detect
}
}
b.MagicConn().SetSilentDisco(b.ControlKnobs().SilentDisco.Load())
b.MagicConn().SetProbeUDPLifetime(b.ControlKnobs().ProbeUDPLifetime.Load())
if buildfeatures.HasDebug {
b.setDebugLogsByCapabilityLocked(nm)
}
// See the netns package for documentation on what these capability do.
netns.SetBindToInterfaceByRoute(b.logf, nm.HasCap(tailcfg.CapabilityBindToInterfaceByRoute))
if runtime.GOOS == "android" {
netns.SetDisableAndroidBindToActiveNetwork(b.logf, nm.HasCap(tailcfg.NodeAttrDisableAndroidBindToActiveNetwork))
}
netns.SetDisableBindConnToInterface(b.logf, nm.HasCap(tailcfg.CapabilityDebugDisableBindConnToInterface))
netns.SetDisableBindConnToInterfaceAppleExt(b.logf, nm.HasCap(tailcfg.CapabilityDebugDisableBindConnToInterfaceAppleExt))
b.setTCPPortsInterceptedFromNetmapAndPrefsLocked(b.pm.CurrentPrefs())
if buildfeatures.HasServe {
m := nm.GetIPVIPServiceMap()
b.ipVIPServiceMap = m
if ns, ok := b.sys.Netstack.GetOK(); ok {
ns.UpdateIPServiceMappings(m)
// In case the prefs reloaded from Profile Manager but didn't change,
// we still need to load the active VIP services into netstack.
ns.UpdateActiveVIPServices(b.pm.CurrentPrefs().AdvertiseServices())
}
}
if !oldSelf.Equal(nm.SelfNodeOrZero()) {
for _, f := range b.extHost.Hooks().OnSelfChange {
f(nm.SelfNode)
}
}
if buildfeatures.HasAdvertiseRoutes {
if nm == nil {
// If there is no netmap, the client is going into a "turned off"
// state so reset the metrics.
b.metrics.approvedRoutes.Set(0)
} else if nm.SelfNode.Valid() {
var approved float64
for _, route := range nm.SelfNode.AllowedIPs().All() {
if !views.SliceContains(nm.SelfNode.Addresses(), route) && !tsaddr.IsExitRoute(route) {
approved++
}
}
b.metrics.approvedRoutes.Set(approved)
}
}
if buildfeatures.HasDrive && nm != nil {
if f, ok := hookSetNetMapLockedDrive.GetOk(); ok {
f(b, nm)
}
}
// Reaching here, we have successfully applied a new network map, and must
// now (if configured) update the cache. We do this after application to
// reduce the chance we will cache a QoD netmap.
//
// As of 2026-03-25 we require the envknob AND the node attribute to use
// a netmap cache, with the envknob defaulted to true so we can use it as
// a safety override during rollout.
//
// We treat the envknob being false as identical to disabling the feature
// by policy, and clean up the cache on that basis. That ensures we will
// not wind up in a situation where we have a stale cached netmap that is
// not being updated (because of the envknob) and could be read back when
// the node starts up.
if nm != nil {
if b.currentNode().SelfHasCap(tailcfg.NodeAttrCacheNetworkMaps) && envknob.BoolDefaultTrue("TS_USE_CACHED_NETMAP") {
if err := b.writeNetmapToDiskLocked(nm); err != nil {
b.logf("write netmap to cache: %v", err)
}
} else {
b.discardDiskCacheLocked()
}
}
}
var hookSetNetMapLockedDrive feature.Hook[func(*LocalBackend, *netmap.NetworkMap)]
// roundTraffic rounds bytes. This is used to preserve user privacy within logs.
func roundTraffic(bytes int64) float64 {
var x float64
switch {
case bytes <= 5:
return float64(bytes)
case bytes < 1000:
x = 10
case bytes < 10_000:
x = 100
case bytes < 100_000:
x = 1000
case bytes < 1_000_000:
x = 10_000
case bytes < 10_000_000:
x = 100_000
case bytes < 100_000_000:
x = 1_000_000
case bytes < 1_000_000_000:
x = 10_000_000
default:
x = 100_000_000
}
return math.Round(float64(bytes)/x) * x
}
// setDebugLogsByCapabilityLocked sets debug logging based on the self node's
// capabilities in the provided NetMap.
func (b *LocalBackend) setDebugLogsByCapabilityLocked(nm *netmap.NetworkMap) {
// These are sufficiently cheap (atomic bools) that we don't need to
// store state and compare.
if nm.HasCap(tailcfg.CapabilityDebugTSDNSResolution) {
dnscache.SetDebugLoggingEnabled(true)
} else {
dnscache.SetDebugLoggingEnabled(false)
}
}
// setTCPPortsInterceptedFromNetmapAndPrefsLocked calls setTCPPortsIntercepted with
// the ports that tailscaled should handle as a function of b.netMap and b.prefs.
//
// b.mu must be held.
func (b *LocalBackend) setTCPPortsInterceptedFromNetmapAndPrefsLocked(prefs ipn.PrefsView) {
handlePorts := make([]uint16, 0, 4)
if prefs.Valid() && prefs.RunSSH() && envknob.CanSSHD() {
handlePorts = append(handlePorts, 22)
}
if b.ShouldExposeRemoteWebClient() {
handlePorts = append(handlePorts, webClientPort)
// don't listen on netmap addresses if we're in userspace mode
if !b.sys.IsNetstack() {
b.updateWebClientListenersLocked()
}
}
if f, ok := hookServeSetTCPPortsInterceptedFromNetmapAndPrefsLocked.GetOk(); ok {
v := f(b, prefs)
handlePorts = append(handlePorts, v...)
}
// Update funnel and service hash info in hostinfo and kick off control update if needed.
b.maybeSentHostinfoIfChangedLocked(prefs)
b.setTCPPortsIntercepted(handlePorts)
}
// hookMaybeMutateHostinfoLocked is a hook that allows conditional features
// to mutate the provided hostinfo before it is sent to control.
//
// The hook function should return true if it mutated the hostinfo.
//
// The LocalBackend's mutex is held while calling.
var hookMaybeMutateHostinfoLocked feature.Hooks[func(*LocalBackend, *tailcfg.Hostinfo, ipn.PrefsView) bool]
// maybeSentHostinfoIfChangedLocked updates the hostinfo.ServicesHash, hostinfo.WireIngress and
// hostinfo.IngressEnabled fields and kicks off a Hostinfo update if the values have changed.
//
// b.mu must be held.
func (b *LocalBackend) maybeSentHostinfoIfChangedLocked(prefs ipn.PrefsView) {
if b.hostinfo == nil {
return
}
changed := false
for _, f := range hookMaybeMutateHostinfoLocked {
if f(b, b.hostinfo, prefs) {
changed = true
}
}
// Kick off a Hostinfo update to control if ingress status has changed.
if changed {
b.goTracker.Go(b.doSetHostinfoFilterServices)
}
}
// OperatorUserName returns the current pref's OperatorUser's name, or the
// empty string if none.
func (b *LocalBackend) OperatorUserName() string {
b.mu.Lock()
defer b.mu.Unlock()
prefs := b.pm.CurrentPrefs()
if !prefs.Valid() {
return ""
}
return prefs.OperatorUser()
}
// OperatorUserID returns the current pref's OperatorUser's ID (in
// os/user.User.Uid string form), or the empty string if none.
func (b *LocalBackend) OperatorUserID() string {
opUserName := b.OperatorUserName()
if opUserName == "" {
return ""
}
u, err := osuser.LookupByUsername(opUserName)
if err != nil {
b.logf("error looking up operator %q uid: %v", opUserName, err)
return ""
}
return u.Uid
}
// TestOnlyPublicKeys returns the current machine and node public
// keys. Used in tests only to facilitate automated node authorization
// in the test harness.
func (b *LocalBackend) TestOnlyPublicKeys() (machineKey key.MachinePublic, nodeKey key.NodePublic) {
b.mu.Lock()
machinePrivKey := b.machinePrivKey
prefs := b.pm.CurrentPrefs()
b.mu.Unlock()
if !prefs.Valid() || machinePrivKey.IsZero() {
return
}
mk := machinePrivKey.Public()
nk := prefs.Persist().PublicNodeKey()
return mk, nk
}
// SetDNS adds a DNS record for the given domain name & TXT record
// value.
//
// It's meant for use with dns-01 ACME (LetsEncrypt) challenges.
//
// This is the low-level interface. Other layers will provide more
// friendly options to get HTTPS certs.
func (b *LocalBackend) SetDNS(ctx context.Context, name, value string) error {
if !buildfeatures.HasACME {
return feature.ErrUnavailable
}
req := &tailcfg.SetDNSRequest{
Version: 1, // TODO(bradfitz,maisem): use tailcfg.CurrentCapabilityVersion when using the Noise transport
Type: "TXT",
Name: name,
Value: value,
}
b.mu.Lock()
cc := b.ccAuto
if prefs := b.pm.CurrentPrefs(); prefs.Valid() && prefs.Persist().Valid() {
req.NodeKey = prefs.Persist().PrivateNodeKey().Public()
}
b.mu.Unlock()
if cc == nil {
return errors.New("not connected")
}
if req.NodeKey.IsZero() {
return errors.New("no nodekey")
}
if name == "" {
return errors.New("missing 'name'")
}
if value == "" {
return errors.New("missing 'value'")
}
return cc.SetDNS(ctx, req)
}
func peerAPIPorts(peer tailcfg.NodeView) (p4, p6 uint16) {
svcs := peer.Hostinfo().Services()
for _, s := range svcs.All() {
switch s.Proto {
case tailcfg.PeerAPI4:
p4 = s.Port
case tailcfg.PeerAPI6:
p6 = s.Port
}
}
return
}
func (b *LocalBackend) CheckIPForwarding() error {
if !buildfeatures.HasAdvertiseRoutes {
return nil
}
if b.sys.IsNetstackRouter() {
return nil
}
// TODO: let the caller pass in the ranges.
warn, err := netutil.CheckIPForwarding(tsaddr.ExitRoutes(), b.sys.NetMon.Get().InterfaceState())
if err != nil {
return err
}
return warn
}
// CheckUDPGROForwarding checks if the machine is optimally configured to
// forward UDP packets between the default route and Tailscale TUN interfaces.
// It returns an error if the check fails or if suboptimal configuration is
// detected. No error is returned if we are unable to gather the interface
// names from the relevant subsystems.
func (b *LocalBackend) CheckUDPGROForwarding() error {
if b.sys.IsNetstackRouter() {
return nil
}
// We return nil when the interface name or subsystem it's tied to can't be
// fetched. This is intentional as answering the question "are netdev
// features optimal for performance?" is a low priority in that situation.
tunSys, ok := b.sys.Tun.GetOK()
if !ok {
return nil
}
tunInterface, err := tunSys.Name()
if err != nil {
return nil
}
netmonSys, ok := b.sys.NetMon.GetOK()
if !ok {
return nil
}
state := netmonSys.InterfaceState()
if state == nil {
return nil
}
// We return warn or err. If err is non-nil there was a problem
// communicating with the kernel via ethtool semantics/ioctl. ethtool ioctl
// errors are interesting for our future selves as we consider tweaking
// netdev features automatically using similar API infra.
warn, err := netkernelconf.CheckUDPGROForwarding(tunInterface, state.DefaultRouteInterface)
if err != nil {
return err
}
return warn
}
// SetUDPGROForwarding enables UDP GRO forwarding for the default network
// interface of this machine. It can be done to improve performance for nodes
// acting as Tailscale subnet routers or exit nodes. Currently (9/5/2024) this
// functionality is considered experimental and only safe to use via explicit
// user opt-in for ephemeral devices, such as containers.
// https://tailscale.com/kb/1320/performance-best-practices#linux-optimizations-for-subnet-routers-and-exit-nodes
func (b *LocalBackend) SetUDPGROForwarding() error {
if b.sys.IsNetstackRouter() {
return errors.New("UDP GRO forwarding cannot be enabled in userspace mode")
}
tunSys, ok := b.sys.Tun.GetOK()
if !ok {
return errors.New("[unexpected] unable to retrieve tun device configuration")
}
tunInterface, err := tunSys.Name()
if err != nil {
return errors.New("[unexpected] unable to determine name of the tun device")
}
netmonSys, ok := b.sys.NetMon.GetOK()
if !ok {
return errors.New("[unexpected] unable to retrieve tailscale netmon configuration")
}
state := netmonSys.InterfaceState()
if state == nil {
return errors.New("[unexpected] unable to retrieve machine's network interface state")
}
if err := netkernelconf.SetUDPGROForwarding(tunInterface, state.DefaultRouteInterface); err != nil {
return fmt.Errorf("error enabling UDP GRO forwarding: %w", err)
}
return nil
}
// DERPMap returns the current DERPMap in use, or nil if not connected.
func (b *LocalBackend) DERPMap() *tailcfg.DERPMap {
return b.currentNode().DERPMap()
}
// OfferingExitNode reports whether b is currently offering exit node
// access.
func (b *LocalBackend) OfferingExitNode() bool {
b.mu.Lock()
defer b.mu.Unlock()
if !b.pm.CurrentPrefs().Valid() {
return false
}
var def4, def6 bool
ar := b.pm.CurrentPrefs().AdvertiseRoutes()
for i := range ar.Len() {
r := ar.At(i)
if r.Bits() != 0 {
continue
}
if r.Addr().Is4() {
def4 = true
} else if r.Addr().Is6() {
def6 = true
}
}
return def4 && def6
}
// OfferingAppConnector reports whether b is currently offering app
// connector services.
func (b *LocalBackend) OfferingAppConnector() bool {
if !buildfeatures.HasAppConnectors {
return false
}
b.mu.Lock()
defer b.mu.Unlock()
return b.appConnector != nil
}
// AppConnector returns the current AppConnector, or nil if not configured.
//
// TODO(nickkhyl): move app connectors to [nodeBackend], or perhaps a feature package?
func (b *LocalBackend) AppConnector() *appc.AppConnector {
if !buildfeatures.HasAppConnectors {
return nil
}
b.mu.Lock()
defer b.mu.Unlock()
return b.appConnector
}
// allowExitNodeDNSProxyToServeName reports whether the Exit Node DNS
// proxy is allowed to serve responses for the provided DNS name.
func (b *LocalBackend) allowExitNodeDNSProxyToServeName(name string) bool {
b.mu.Lock()
defer b.mu.Unlock()
nm := b.NetMap()
if nm == nil {
return false
}
name = strings.ToLower(name)
for _, bad := range nm.DNS.ExitNodeFilteredSet {
if bad == "" {
// Invalid, ignore.
continue
}
if bad[0] == '.' {
// Entries beginning with a dot are suffix matches.
if dnsname.HasSuffix(name, bad) {
return false
}
continue
}
// Otherwise entries are exact matches. They're
// guaranteed to be lowercase already.
if name == bad {
return false
}
}
return true
}
// SetExpiry updates the expiry of the current node key to t, as long as it's
// only sooner than the old expiry.
//
// If t is in the past, the key is expired immediately.
// If t is after the current expiry, an error is returned.
func (b *LocalBackend) SetExpirySooner(ctx context.Context, expiry time.Time) error {
b.mu.Lock()
cc := b.ccAuto
b.mu.Unlock()
if cc == nil {
return errors.New("not running")
}
return cc.SetExpirySooner(ctx, expiry)
}
// SetDeviceAttrs does a synchronous call to the control plane to update
// the node's attributes.
//
// See docs on [tailcfg.SetDeviceAttributesRequest] for background.
func (b *LocalBackend) SetDeviceAttrs(ctx context.Context, attrs tailcfg.AttrUpdate) error {
b.mu.Lock()
cc := b.ccAuto
b.mu.Unlock()
if cc == nil {
return errors.New("not running")
}
return cc.SetDeviceAttrs(ctx, attrs)
}
// exitNodeCanProxyDNS reports the DoH base URL ("http://foo/dns-query") without query parameters
// to exitNodeID's DoH service, if available.
//
// If exitNodeID is the zero valid, it returns "", false.
func exitNodeCanProxyDNS(nm *netmap.NetworkMap, peers map[tailcfg.NodeID]tailcfg.NodeView, exitNodeID tailcfg.StableNodeID) (dohURL string, ok bool) {
if !buildfeatures.HasUseExitNode {
return "", false
}
if exitNodeID.IsZero() {
return "", false
}
for _, p := range peers {
if p.StableID() == exitNodeID && peerCanProxyDNS(p) {
return peerAPIBase(nm, p) + "/dns-query", true
}
}
return "", false
}
// wireguardExitNodeDNSResolvers returns the DNS resolvers to use for a
// WireGuard-only exit node, if it has resolver addresses.
func wireguardExitNodeDNSResolvers(nm *netmap.NetworkMap, peers map[tailcfg.NodeID]tailcfg.NodeView, exitNodeID tailcfg.StableNodeID) ([]*dnstype.Resolver, bool) {
if exitNodeID.IsZero() {
return nil, false
}
for _, p := range peers {
if p.StableID() == exitNodeID {
if p.IsWireGuardOnly() {
resolvers := p.ExitNodeDNSResolvers()
if !resolvers.IsNil() && resolvers.Len() > 0 {
copies := make([]*dnstype.Resolver, resolvers.Len())
for i, r := range resolvers.All() {
copies[i] = r.AsStruct()
}
return copies, true
}
}
return nil, false
}
}
return nil, false
}
func peerCanProxyDNS(p tailcfg.NodeView) bool {
if p.Cap() >= 26 {
// Actually added at 25
// (https://github.com/tailscale/tailscale/blob/3ae6f898cfdb58fd0e30937147dd6ce28c6808dd/tailcfg/tailcfg.go#L51)
// so anything >= 26 can do it.
return true
}
// If p.Cap is not populated (e.g. older control server), then do the old
// thing of searching through services.
services := p.Hostinfo().Services()
for _, s := range services.All() {
if s.Proto == tailcfg.PeerAPIDNS && s.Port >= 1 {
return true
}
}
return false
}
func (b *LocalBackend) DebugRebind() error {
b.MagicConn().Rebind()
return nil
}
func (b *LocalBackend) DebugReSTUN() error {
b.MagicConn().ReSTUN("explicit-debug")
return nil
}
func (b *LocalBackend) DebugRotateDiscoKey() error {
if !buildfeatures.HasDebug {
return nil
}
mc := b.MagicConn()
mc.RotateDiscoKey()
newDiscoKey := mc.DiscoPublicKey()
if tunWrap, ok := b.sys.Tun.GetOK(); ok {
tunWrap.SetDiscoKey(newDiscoKey)
}
b.mu.Lock()
cc := b.cc
b.mu.Unlock()
if cc != nil {
cc.SetDiscoPublicKey(newDiscoKey)
}
return nil
}
func (b *LocalBackend) DebugPeerRelayServers() set.Set[netip.Addr] {
return b.MagicConn().PeerRelays()
}
// ControlKnobs returns the node's control knobs.
func (b *LocalBackend) ControlKnobs() *controlknobs.Knobs {
return b.sys.ControlKnobs()
}
// EventBus returns the node's event bus.
func (b *LocalBackend) EventBus() *eventbus.Bus {
return b.sys.Bus.Get()
}
// MagicConn returns the backend's *magicsock.Conn.
func (b *LocalBackend) MagicConn() *magicsock.Conn {
return b.sys.MagicSock.Get()
}
// DoNoiseRequest sends a request to URL over the control plane
// Noise connection.
func (b *LocalBackend) DoNoiseRequest(req *http.Request) (*http.Response, error) {
b.mu.Lock()
cc := b.ccAuto
b.mu.Unlock()
if cc == nil {
return nil, errors.New("no client")
}
return cc.DoNoiseRequest(req)
}
// ActiveSSHConns returns the number of active SSH connections,
// or 0 if SSH is not linked into the binary or available on the platform.
func (b *LocalBackend) ActiveSSHConns() int {
if b.sshServer == nil {
return 0
}
return b.sshServer.NumActiveConns()
}
func (b *LocalBackend) sshServerOrInit() (_ SSHServer, err error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.sshServer != nil {
return b.sshServer, nil
}
if newSSHServer == nil {
return nil, errors.New("no SSH server support")
}
b.sshServer, err = newSSHServer(b.logf, b)
if err != nil {
return nil, fmt.Errorf("newSSHServer: %w", err)
}
return b.sshServer, nil
}
var warnSyncDisabled = health.Register(&health.Warnable{
Code: "sync-disabled",
Title: "Tailscale Sync is Disabled",
Severity: health.SeverityHigh,
Text: health.StaticMessage("Tailscale control plane syncing is disabled; run `tailscale set --sync` to restore"),
})
var warnSSHSELinuxWarnable = health.Register(&health.Warnable{
Code: "ssh-unavailable-selinux-enabled",
Title: "Tailscale SSH and SELinux",
Severity: health.SeverityLow,
Text: health.StaticMessage("SELinux is enabled; Tailscale SSH may not work. See https://tailscale.com/s/ssh-selinux"),
})
// warnNoSNATWithExitNode is a warnable for when a node is advertising as an
// exit node but has SNAT disabled. In this configuration internet-bound traffic
// from peers using this exit node will not be masqueraded to the node's own
// source IP, so return packets cannot be routed back, causing the exit node to
// not work as expected.
var warnNoSNATWithExitNode = health.Register(&health.Warnable{
Code: "nosnat-with-advertised-exit-node",
Title: "Exit node advertising may not work correctly",
Severity: health.SeverityMedium,
Text: health.StaticMessage("snat-subnet-routes is disabled while advertising as an exit node; internet traffic through this exit node may not work as expected"),
})
func (b *LocalBackend) updateSELinuxHealthWarning() {
if hostinfo.IsSELinuxEnforcing() {
b.health.SetUnhealthy(warnSSHSELinuxWarnable, nil)
} else {
b.health.SetHealthy(warnSSHSELinuxWarnable)
}
}
func (b *LocalBackend) updateWarnSync(prefs ipn.PrefsView) {
if prefs.Sync().EqualBool(false) {
b.health.SetUnhealthy(warnSyncDisabled, nil)
} else {
b.health.SetHealthy(warnSyncDisabled)
}
}
func (b *LocalBackend) updateNoSNATExitNodeWarning(prefs ipn.PrefsView) {
if !buildfeatures.HasAdvertiseExitNode {
return
}
if prefs.NoSNAT() && prefs.AdvertisesExitNode() {
b.health.SetUnhealthy(warnNoSNATWithExitNode, nil)
} else {
b.health.SetHealthy(warnNoSNATWithExitNode)
}
}
func (b *LocalBackend) handleSSHConn(c net.Conn) (err error) {
s, err := b.sshServerOrInit()
if err != nil {
return err
}
b.updateSELinuxHealthWarning()
return s.HandleSSHConn(c)
}
// HandleQuad100Port80Conn serves http://100.100.100.100/ on port 80 (and
// the equivalent tsaddr.TailscaleServiceIPv6 address).
func (b *LocalBackend) HandleQuad100Port80Conn(c net.Conn) error {
var s http.Server
s.Handler = http.HandlerFunc(b.handleQuad100Port80Conn)
return s.Serve(netutil.NewOneConnListener(c, nil))
}
func validQuad100Host(h string) bool {
switch h {
case "",
tsaddr.TailscaleServiceIPString,
tsaddr.TailscaleServiceIPv6String,
"[" + tsaddr.TailscaleServiceIPv6String + "]":
return true
}
return false
}
func (b *LocalBackend) handleQuad100Port80Conn(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Content-Security-Policy", "default-src 'self';")
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !validQuad100Host(r.Host) {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
b.mu.Lock()
defer b.mu.Unlock()
io.WriteString(w, "<h1>Tailscale</h1>\n")
nm := b.currentNode().NetMap()
if nm == nil {
io.WriteString(w, "No netmap.\n")
return
}
addrs := nm.GetAddresses()
if addrs.Len() == 0 {
io.WriteString(w, "No local addresses.\n")
return
}
io.WriteString(w, "<p>Local addresses:</p><ul>\n")
for i := range addrs.Len() {
fmt.Fprintf(w, "<li>%v</li>\n", addrs.At(i).Addr())
}
io.WriteString(w, "</ul>\n")
}
// HookDoctor is an optional hook for the "doctor" problem diagnosis feature.
var HookDoctor feature.Hook[func(context.Context, *LocalBackend, logger.Logf)]
// SetDevStateStore updates the LocalBackend's state storage to the provided values.
//
// It's meant only for development.
func (b *LocalBackend) SetDevStateStore(key, value string) error {
if b.store == nil {
return errors.New("no state store")
}
err := ipn.WriteState(b.store, ipn.StateKey(key), []byte(value))
b.logf("SetDevStateStore(%q, %q) = %v", key, value, err)
if err != nil {
return err
}
b.mu.Lock()
defer b.mu.Unlock()
b.setTCPPortsInterceptedFromNetmapAndPrefsLocked(b.pm.CurrentPrefs())
return nil
}
// ShouldInterceptTCPPort reports whether the given TCP port number to a
// Tailscale IP (not a subnet router, service IP, etc) should be intercepted by
// Tailscaled and handled in-process.
func (b *LocalBackend) ShouldInterceptTCPPort(port uint16) bool {
return b.shouldInterceptTCPPortAtomic.Load()(port)
}
// ShouldInterceptVIPServiceTCPPort reports whether the given TCP port number
// to a VIP service should be intercepted by Tailscaled and handled in-process.
func (b *LocalBackend) ShouldInterceptVIPServiceTCPPort(ap netip.AddrPort) bool {
if !buildfeatures.HasServe {
return false
}
f := b.shouldInterceptVIPServicesTCPPortAtomic.Load()
if f == nil {
return false
}
return f(ap)
}
// SwitchProfile switches to the profile with the given id.
// It will restart the backend on success.
// If the profile is not known, it returns an errProfileNotFound.
func (b *LocalBackend) SwitchProfile(profile ipn.ProfileID) error {
b.mu.Lock()
defer b.mu.Unlock()
oldControlURL := b.pm.CurrentPrefs().ControlURLOrDefault(b.polc)
if _, changed, err := b.pm.SwitchToProfileByID(profile); !changed || err != nil {
return err // nil if we're already on the target profile
}
// As an optimization, only reset the dialPlan if the control URL changed.
if newControlURL := b.pm.CurrentPrefs().ControlURLOrDefault(b.polc); oldControlURL != newControlURL {
b.resetDialPlan()
}
return b.resetForProfileChangeLocked()
}
// resetDialPlan resets the dialPlan for this LocalBackend. It will log if
// anything is reset.
//
// It is safe to call this concurrently, with or without b.mu held.
func (b *LocalBackend) resetDialPlan() {
old := b.dialPlan.Swap(nil)
if old != nil {
b.logf("resetDialPlan: did reset")
}
}
// resetForProfileChangeLocked resets the backend for a profile change.
//
// b.mu must be held.
func (b *LocalBackend) resetForProfileChangeLocked() error {
if b.shutdownCalled {
// Prevent a call back to Start during Shutdown, which calls Logout for
// ephemeral nodes, which can then call back here. But we're shutting
// down, so no need to do any work.
return nil
}
newNode := newNodeBackend(b.ctx, b.logf, b.sys.Bus.Get())
if oldNode := b.currentNodeAtomic.Swap(newNode); oldNode != nil {
oldNode.shutdown(errNodeContextChanged)
}
defer newNode.ready()
b.setNetMapLocked(nil) // Reset netmap.
b.updateFilterLocked(ipn.PrefsView{})
// Reset the NetworkMap in the engine
b.e.SetNetworkMap(new(netmap.NetworkMap))
if prevCC := b.resetControlClientLocked(); prevCC != nil {
// Shutdown outside of b.mu to avoid deadlocks.
b.goTracker.Go(prevCC.Shutdown)
}
// TKA errors should not prevent resetting the backend state.
// However, we should still return the error to the caller.
tkaErr := b.initTKALocked()
b.lastServeConfJSON = mem.B(nil)
b.serveConfig = ipn.ServeConfigView{}
b.lastSuggestedExitNode = ""
b.keyExpired = false
b.overrideExitNodePolicy = false
b.resetAlwaysOnOverrideLocked()
b.extHost.NotifyProfileChange(b.pm.CurrentProfile(), b.pm.CurrentPrefs(), false)
b.setAtomicValuesFromPrefsLocked(b.pm.CurrentPrefs())
b.enterStateLocked(ipn.NoState)
b.health.SetLocalLogConfigHealth(nil)
if tkaErr != nil {
return tkaErr
}
return b.startLocked(ipn.Options{})
}
// DeleteProfile deletes a profile with the given ID.
// If the profile is not known, it is a no-op.
func (b *LocalBackend) DeleteProfile(p ipn.ProfileID) error {
b.mu.Lock()
defer b.mu.Unlock()
needToRestart := b.pm.CurrentProfile().ID() == p
if err := b.pm.DeleteProfile(p); err != nil {
if err == errProfileNotFound {
return nil
}
return err
}
// Make a best-effort to remove the profile-specific data directory, if one exists.
if pd := b.profileDataPathLocked(p); pd != "" {
if err := os.RemoveAll(pd); err != nil {
b.logf("warning: removing profile data for %q: %v", p, err)
}
}
if !needToRestart {
return nil
}
return b.resetForProfileChangeLocked()
}
// CurrentProfile returns the current LoginProfile.
// The value may be zero if the profile is not persisted.
func (b *LocalBackend) CurrentProfile() ipn.LoginProfileView {
b.mu.Lock()
defer b.mu.Unlock()
return b.pm.CurrentProfile()
}
// NewProfile creates and switches to the new profile.
func (b *LocalBackend) NewProfile() error {
if b.health.IsUnhealthy(ipn.StateStoreHealth) {
return errors.New("cannot log in when state store is unhealthy")
}
b.mu.Lock()
defer b.mu.Unlock()
b.pm.SwitchToNewProfile()
// The new profile doesn't yet have a ControlURL because it hasn't been
// set. Conservatively reset the dialPlan.
b.resetDialPlan()
return b.resetForProfileChangeLocked()
}
// ListProfiles returns a list of all LoginProfiles.
func (b *LocalBackend) ListProfiles() []ipn.LoginProfileView {
b.mu.Lock()
defer b.mu.Unlock()
return b.pm.Profiles()
}
// ResetAuth resets the authentication state, including persisted keys. Also
// has the side effect of removing all profiles and reseting preferences. The
// backend is left with a new profile, ready for StartLoginInterative to be
// called to register it as new node.
func (b *LocalBackend) ResetAuth() error {
b.mu.Lock()
defer b.mu.Unlock()
if prevCC := b.resetControlClientLocked(); prevCC != nil {
// Shutdown outside of b.mu to avoid deadlocks.
b.goTracker.Go(prevCC.Shutdown)
}
if err := b.clearMachineKeyLocked(); err != nil {
return err
}
if err := b.pm.DeleteAllProfilesForUser(); err != nil {
return err
}
b.resetDialPlan() // always reset if we're removing everything
return b.resetForProfileChangeLocked()
}
func (b *LocalBackend) GetPeerEndpointChanges(ctx context.Context, ip netip.Addr) ([]magicsock.EndpointChange, error) {
pip, ok := b.e.PeerForIP(ip)
if !ok {
return nil, fmt.Errorf("no matching peer")
}
if pip.IsSelf {
return nil, fmt.Errorf("%v is local Tailscale IP", ip)
}
peer := pip.Node
chs, err := b.MagicConn().GetEndpointChanges(peer)
if err != nil {
return nil, fmt.Errorf("getting endpoint changes: %w", err)
}
return chs, nil
}
var breakTCPConns func() error
func (b *LocalBackend) DebugBreakTCPConns() error {
if breakTCPConns == nil {
return errors.New("TCP connection breaking not available on this platform")
}
return breakTCPConns()
}
func (b *LocalBackend) DebugBreakDERPConns() error {
return b.MagicConn().DebugBreakDERPConns()
}
// ObserveDNSResponse passes a DNS response from the PeerAPI DNS server to the
// App Connector to enable route discovery.
func (b *LocalBackend) ObserveDNSResponse(res []byte) error {
if !buildfeatures.HasAppConnectors {
return nil
}
var appConnector *appc.AppConnector
b.mu.Lock()
if b.appConnector == nil {
b.mu.Unlock()
return nil
}
appConnector = b.appConnector
b.mu.Unlock()
return appConnector.ObserveDNSResponse(res)
}
// ErrDisallowedAutoRoute is returned by AdvertiseRoute when a route that is not allowed is requested.
var ErrDisallowedAutoRoute = errors.New("route is not allowed")
// AdvertiseRoute implements the appctype.RouteAdvertiser interface. It sets a
// new route advertisement if one is not already present in the existing
// routes. If the route is disallowed, ErrDisallowedAutoRoute is returned.
func (b *LocalBackend) AdvertiseRoute(ipps ...netip.Prefix) error {
finalRoutes := b.Prefs().AdvertiseRoutes().AsSlice()
var newRoutes []netip.Prefix
for _, ipp := range ipps {
if ipp != ipp.Masked() {
return fmt.Errorf("route %s has non-address bits set; expected %s", ipp, ipp.Masked())
}
if !allowedAutoRoute(ipp) {
continue
}
if slices.Contains(finalRoutes, ipp) {
continue
}
// If the new prefix is already contained by existing routes, skip it.
if coveredRouteRangeNoDefault(finalRoutes, ipp) {
continue
}
finalRoutes = append(finalRoutes, ipp)
newRoutes = append(newRoutes, ipp)
}
if len(newRoutes) == 0 {
return nil
}
b.logf("advertising new app connector routes: %v", newRoutes)
_, err := b.EditPrefs(&ipn.MaskedPrefs{
Prefs: ipn.Prefs{
AdvertiseRoutes: finalRoutes,
},
AdvertiseRoutesSet: true,
})
return err
}
// coveredRouteRangeNoDefault checks if a route is already included in a slice of
// prefixes, ignoring default routes in the range.
func coveredRouteRangeNoDefault(finalRoutes []netip.Prefix, ipp netip.Prefix) bool {
for _, r := range finalRoutes {
if r == tsaddr.AllIPv4() || r == tsaddr.AllIPv6() {
continue
}
if ipp.IsSingleIP() {
if r.Contains(ipp.Addr()) {
return true
}
} else {
if r.Contains(ipp.Addr()) && r.Contains(netipx.PrefixLastIP(ipp)) {
return true
}
}
}
return false
}
// UnadvertiseRoute implements the appctype.RouteAdvertiser interface. It
// removes a route advertisement if one is present in the existing routes.
func (b *LocalBackend) UnadvertiseRoute(toRemove ...netip.Prefix) error {
currentRoutes := b.Prefs().AdvertiseRoutes().AsSlice()
finalRoutes := currentRoutes[:0]
for _, ipp := range currentRoutes {
if slices.Contains(toRemove, ipp) {
continue
}
finalRoutes = append(finalRoutes, ipp)
}
_, err := b.EditPrefs(&ipn.MaskedPrefs{
Prefs: ipn.Prefs{
AdvertiseRoutes: finalRoutes,
},
AdvertiseRoutesSet: true,
})
return err
}
// namespace a key with the profile manager's current profile key, if any
func namespaceKeyForCurrentProfile(pm *profileManager, key ipn.StateKey) ipn.StateKey {
return pm.CurrentProfile().Key() + "||" + key
}
const routeInfoStateStoreKey ipn.StateKey = "_routeInfo"
func (b *LocalBackend) storeRouteInfo(ri appctype.RouteInfo) error {
if !buildfeatures.HasAppConnectors {
return feature.ErrUnavailable
}
b.mu.Lock()
defer b.mu.Unlock()
if b.pm.CurrentProfile().ID() == "" {
return nil
}
key := namespaceKeyForCurrentProfile(b.pm, routeInfoStateStoreKey)
bs, err := json.Marshal(ri)
if err != nil {
return err
}
return b.pm.WriteState(key, bs)
}
func (b *LocalBackend) readRouteInfoLocked() (*appctype.RouteInfo, error) {
if !buildfeatures.HasAppConnectors {
return nil, feature.ErrUnavailable
}
if b.pm.CurrentProfile().ID() == "" {
return &appctype.RouteInfo{}, nil
}
key := namespaceKeyForCurrentProfile(b.pm, routeInfoStateStoreKey)
bs, err := b.pm.Store().ReadState(key)
ri := &appctype.RouteInfo{}
if err != nil {
return nil, err
}
if err := json.Unmarshal(bs, ri); err != nil {
return nil, err
}
return ri, nil
}
// ReadRouteInfo returns the app connector route information that is
// stored in prefs to be consistent across restarts. It should be up
// to date with the RouteInfo in memory being used by appc.
func (b *LocalBackend) ReadRouteInfo() (*appctype.RouteInfo, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.readRouteInfoLocked()
}
// seamlessRenewalEnabled reports whether seamless key renewals are enabled.
//
// As of 2025-09-11, this is the default behaviour unless nodes receive
// [tailcfg.NodeAttrDisableSeamlessKeyRenewal] in their netmap.
func (b *LocalBackend) seamlessRenewalEnabled() bool {
return b.ControlKnobs().SeamlessKeyRenewal.Load()
}
var (
disallowedAddrs = []netip.Addr{
netip.MustParseAddr("::1"),
netip.MustParseAddr("::"),
netip.MustParseAddr("0.0.0.0"),
}
disallowedRanges = []netip.Prefix{
netip.MustParsePrefix("127.0.0.0/8"),
netip.MustParsePrefix("224.0.0.0/4"),
netip.MustParsePrefix("ff00::/8"),
}
)
// allowedAutoRoute determines if the route being added via AdvertiseRoute (the app connector featuge) should be allowed.
func allowedAutoRoute(ipp netip.Prefix) bool {
// Note: blocking the addrs for globals, not solely the prefixes.
if slices.Contains(disallowedAddrs, ipp.Addr()) {
return false
}
for _, pfx := range disallowedRanges {
if pfx.Overlaps(ipp) {
return false
}
}
// TODO(raggi): exclude tailscale service IPs and so on as well.
return true
}
var ErrNoPreferredDERP = errors.New("no preferred DERP, try again later")
// suggestExitNodeLocked computes a suggestion based on the current netmap and
// other optional factors. If there are multiple equally good options, one may
// be selected at random, so the result is not stable. To be eligible for
// consideration, the peer must have NodeAttrSuggestExitNode in its CapMap.
//
// b.mu must be held.
func (b *LocalBackend) suggestExitNodeLocked() (response apitype.ExitNodeSuggestionResponse, err error) {
if !buildfeatures.HasUseExitNode {
return response, feature.ErrUnavailable
}
lastReport := b.MagicConn().GetLastNetcheckReport(b.ctx)
prevSuggestion := b.lastSuggestedExitNode
res, err := suggestExitNode(lastReport, b.currentNode(), prevSuggestion, randomRegion, randomNode, b.getAllowedSuggestions())
if err != nil {
return res, err
}
if prevSuggestion != res.ID {
// Notify the clients via the IPN bus if the exit node suggestion has changed.
b.sendToLocked(ipn.Notify{SuggestedExitNode: &res.ID}, allClients)
}
b.lastSuggestedExitNode = res.ID
return res, err
}
func (b *LocalBackend) SuggestExitNode() (response apitype.ExitNodeSuggestionResponse, err error) {
if !buildfeatures.HasUseExitNode {
return response, feature.ErrUnavailable
}
b.mu.Lock()
defer b.mu.Unlock()
return b.suggestExitNodeLocked()
}
// getAllowedSuggestions returns a set of exit nodes permitted by the most recent
// [pkey.AllowedSuggestedExitNodes] value. Callers must not mutate the returned set.
func (b *LocalBackend) getAllowedSuggestions() set.Set[tailcfg.StableNodeID] {
b.allowedSuggestedExitNodesMu.Lock()
defer b.allowedSuggestedExitNodesMu.Unlock()
return b.allowedSuggestedExitNodes
}
// refreshAllowedSuggestions rebuilds the set of permitted exit nodes
// from the current [pkey.AllowedSuggestedExitNodes] value.
func (b *LocalBackend) refreshAllowedSuggestions() {
if !buildfeatures.HasUseExitNode {
return
}
b.allowedSuggestedExitNodesMu.Lock()
defer b.allowedSuggestedExitNodesMu.Unlock()
var err error
b.allowedSuggestedExitNodes, err = fillAllowedSuggestions(b.polc)
if err != nil {
b.logf("error refreshing allowed suggestions: %v", err)
}
}
// selectRegionFunc returns a DERP region from the slice of candidate regions.
// The value is returned, not the slice index.
type selectRegionFunc func(views.Slice[int]) int
// selectNodeFunc returns a node from the slice of candidate nodes. The last
// selected node is provided for when that information is needed to make a better
// choice.
type selectNodeFunc func(nodes views.Slice[tailcfg.NodeView], last tailcfg.StableNodeID) tailcfg.NodeView
func fillAllowedSuggestions(polc policyclient.Client) (set.Set[tailcfg.StableNodeID], error) {
nodes, err := polc.GetStringArray(pkey.AllowedSuggestedExitNodes, nil)
if err != nil {
return nil, fmt.Errorf("fillAllowedSuggestions: unable to look up %q policy: %w", pkey.AllowedSuggestedExitNodes, err)
}
if nodes == nil {
return nil, nil
}
s := make(set.Set[tailcfg.StableNodeID], len(nodes))
for _, n := range nodes {
s.Add(tailcfg.StableNodeID(n))
}
return s, nil
}
// suggestExitNode returns a suggestion for reasonably good exit node based on
// the current netmap and the previous suggestion.
func suggestExitNode(report *netcheck.Report, nb *nodeBackend, prevSuggestion tailcfg.StableNodeID, selectRegion selectRegionFunc, selectNode selectNodeFunc, allowList set.Set[tailcfg.StableNodeID]) (res apitype.ExitNodeSuggestionResponse, err error) {
switch {
case nb.SelfHasCap(tailcfg.NodeAttrTrafficSteering):
// The traffic-steering feature flag is enabled on this tailnet.
res, err = suggestExitNodeUsingTrafficSteering(nb, allowList)
default:
// The control plane will always strip the `traffic-steering`
// node attribute if it isn’t enabled for this tailnet, even if
// it is set in the policy file: tailscale/corp#34401
res, err = suggestExitNodeUsingDERP(report, nb, prevSuggestion, selectRegion, selectNode, allowList)
}
if err != nil {
nb.logf("netmap: suggested exit node: %v", err)
} else {
name, _, _ := strings.Cut(res.Name, ".")
nb.logf("netmap: suggested exit node: %s (%s)", name, res.ID)
}
return res, err
}
// suggestExitNodeUsingDERP is the classic algorithm used to suggest exit nodes,
// before traffic steering was implemented. This handles the plain failover
// case, in addition to the optional Regional Routing.
//
// It computes a suggestion based on the current netmap and last netcheck
// report. If there are multiple equally good options, one is selected at
// random, so the result is not stable. To be eligible for consideration, the
// peer must have NodeAttrSuggestExitNode in its CapMap.
//
// Currently, peers with a DERP home are preferred over those without (typically
// this means Mullvad). Peers are selected based on having a DERP home that is
// the lowest latency to this device. For peers without a DERP home, we look for
// geographic proximity to this device's DERP home.
func suggestExitNodeUsingDERP(report *netcheck.Report, nb *nodeBackend, prevSuggestion tailcfg.StableNodeID, selectRegion selectRegionFunc, selectNode selectNodeFunc, allowList set.Set[tailcfg.StableNodeID]) (res apitype.ExitNodeSuggestionResponse, err error) {
// TODO(sfllaw): Context needs to be plumbed down here to support
// reachability testing.
ctx := context.TODO()
netMap := nb.NetMap()
if report == nil || report.PreferredDERP == 0 || netMap == nil || netMap.DERPMap == nil {
return res, ErrNoPreferredDERP
}
// Use [nodeBackend.AppendMatchingPeers] instead of the netmap directly,
// since the netmap doesn't include delta updates (e.g., home DERP or Online
// status changes) from the control plane since the last full update.
candidates := nb.AppendMatchingPeers(nil, func(peer tailcfg.NodeView) bool {
if !peer.Valid() || !nb.PeerIsReachable(ctx, peer) {
return false
}
if allowList != nil && !allowList.Contains(peer.StableID()) {
return false
}
return peer.CapMap().Contains(tailcfg.NodeAttrSuggestExitNode) && tsaddr.ContainsExitRoutes(peer.AllowedIPs())
})
if len(candidates) == 0 {
return res, nil
}
if len(candidates) == 1 {
peer := candidates[0]
if hi := peer.Hostinfo(); hi.Valid() {
if loc := hi.Location(); loc.Valid() {
res.Location = loc
}
}
res.ID = peer.StableID()
res.Name = peer.Name()
return res, nil
}
candidatesByRegion := make(map[int][]tailcfg.NodeView, len(netMap.DERPMap.Regions))
preferredDERP, ok := netMap.DERPMap.Regions[report.PreferredDERP]
if !ok {
return res, ErrNoPreferredDERP
}
var minDistance float64 = math.MaxFloat64
type nodeDistance struct {
nv tailcfg.NodeView
distance float64 // in meters, approximately
}
distances := make([]nodeDistance, 0, len(candidates))
for _, c := range candidates {
if regionID := c.HomeDERP(); regionID != 0 {
candidatesByRegion[regionID] = append(candidatesByRegion[regionID], c)
continue
}
if len(candidatesByRegion) > 0 {
// Since a candidate exists that does have a DERP home, skip this candidate. We never select
// a candidate without a DERP home if there is a candidate available with a DERP home.
continue
}
// This candidate does not have a DERP home.
// Use geographic distance from our DERP home to estimate how good this candidate is.
hi := c.Hostinfo()
if !hi.Valid() {
continue
}
loc := hi.Location()
if !loc.Valid() {
continue
}
distance := longLatDistance(preferredDERP.Latitude, preferredDERP.Longitude, loc.Latitude(), loc.Longitude())
if distance < minDistance {
minDistance = distance
}
distances = append(distances, nodeDistance{nv: c, distance: distance})
}
// First, try to select an exit node that has the closest DERP home, based on lastReport's DERP latency.
// If there are no latency values, it returns an arbitrary region
if len(candidatesByRegion) > 0 {
minRegion := minLatencyDERPRegion(slicesx.MapKeys(candidatesByRegion), report)
if minRegion == 0 {
minRegion = selectRegion(views.SliceOf(slicesx.MapKeys(candidatesByRegion)))
}
regionCandidates, ok := candidatesByRegion[minRegion]
if !ok {
return res, errors.New("no candidates in expected region: this is a bug")
}
chosen := selectNode(views.SliceOf(regionCandidates), prevSuggestion)
res.ID = chosen.StableID()
res.Name = chosen.Name()
if hi := chosen.Hostinfo(); hi.Valid() {
if loc := hi.Location(); loc.Valid() {
res.Location = loc
}
}
return res, nil
}
// None of the candidates have a DERP home, so proceed to select based on geographical distance from our preferred DERP region.
// allowanceMeters is the extra distance that will be permitted when considering peers. By this point, there
// are multiple approximations taking place (DERP location standing in for this device's location, the peer's
// location may only be city granularity, the distance algorithm assumes a spherical planet, etc.) so it is
// reasonable to consider peers that are similar distances. Those peers are good enough to be within
// measurement error. 100km corresponds to approximately 1ms of additional round trip light
// propagation delay in a fiber optic cable and seems like a reasonable heuristic. It may be adjusted in
// future.
const allowanceMeters = 100000
pickFrom := make([]tailcfg.NodeView, 0, len(distances))
for _, candidate := range distances {
if candidate.nv.Valid() && candidate.distance <= minDistance+allowanceMeters {
pickFrom = append(pickFrom, candidate.nv)
}
}
bestCandidates := pickWeighted(pickFrom)
// We may have an empty list of candidates here, if none of the candidates
// have home DERP info.
//
// We know that candidates is non-empty or we'd already have returned, so if
// we've filtered everything out of bestCandidates, just use candidates.
if len(bestCandidates) == 0 {
bestCandidates = candidates
}
chosen := selectNode(views.SliceOf(bestCandidates), prevSuggestion)
if !chosen.Valid() {
return res, errors.New("chosen candidate invalid: this is a bug")
}
res.ID = chosen.StableID()
res.Name = chosen.Name()
if hi := chosen.Hostinfo(); hi.Valid() {
if loc := hi.Location(); loc.Valid() {
res.Location = loc
}
}
return res, nil
}
var ErrNoNetMap = errors.New("no network map, try again later")
// suggestExitNodeUsingTrafficSteering uses traffic steering priority scores to
// pick one of the best exit nodes. These priorities are provided by Control in
// the node’s [tailcfg.Location]. To be eligible for consideration, the node
// must have NodeAttrSuggestExitNode in its CapMap.
func suggestExitNodeUsingTrafficSteering(nb *nodeBackend, allowed set.Set[tailcfg.StableNodeID]) (apitype.ExitNodeSuggestionResponse, error) {
// TODO(sfllaw): Context needs to be plumbed down here to support
// reachability testing.
ctx := context.TODO()
nm := nb.NetMap()
if nm == nil {
return apitype.ExitNodeSuggestionResponse{}, ErrNoNetMap
}
self := nb.Self()
if !self.Valid() {
return apitype.ExitNodeSuggestionResponse{}, ErrNoNetMap
}
if !nb.SelfHasCap(tailcfg.NodeAttrTrafficSteering) {
panic("missing traffic-steering capability")
}
nodes := nb.AppendMatchingPeers(nil, func(p tailcfg.NodeView) bool {
if !p.Valid() {
return false
}
if !nb.PeerIsReachable(ctx, p) {
return false
}
if allowed != nil && !allowed.Contains(p.StableID()) {
return false
}
if !p.CapMap().Contains(tailcfg.NodeAttrSuggestExitNode) {
return false
}
if !tsaddr.ContainsExitRoutes(p.AllowedIPs()) {
return false
}
return true
})
scores := make(map[tailcfg.NodeID]int, len(nodes))
score := func(n tailcfg.NodeView) int {
id := n.ID()
s, ok := scores[id]
if !ok {
s = 0 // score of zero means incomparable
if hi := n.Hostinfo(); hi.Valid() {
if loc := hi.Location(); loc.Valid() {
s = loc.Priority()
}
}
scores[id] = s
}
return s
}
rdvHash := makeRendezvousHasher(self.ID())
var pick tailcfg.NodeView
if len(nodes) == 1 {
pick = nodes[0]
}
if len(nodes) > 1 {
// Find the highest scoring exit nodes.
slices.SortFunc(nodes, func(a, b tailcfg.NodeView) int {
c := cmp.Compare(score(b), score(a)) // Highest score first.
if c == 0 {
// Rendezvous hashing for reliably picking the
// same node from a list: tailscale/tailscale#16551.
return cmp.Compare(rdvHash(b.ID()), rdvHash(a.ID()))
}
return c
})
// TODO(sfllaw): add a temperature knob so that this client has
// a chance of picking the next best option.
pick = nodes[0]
}
nb.logf("netmap: traffic steering: exit node scores: %v", logger.ArgWriter(func(bw *bufio.Writer) {
const max = 10
for i, n := range nodes {
if i == max {
fmt.Fprintf(bw, "... +%d", len(nodes)-max)
return
}
if i > 0 {
bw.WriteString(", ")
}
name, _, _ := strings.Cut(n.Name(), ".")
fmt.Fprintf(bw, "%d:%s", score(n), name)
}
}))
if !pick.Valid() {
return apitype.ExitNodeSuggestionResponse{}, nil
}
res := apitype.ExitNodeSuggestionResponse{
ID: pick.StableID(),
Name: pick.Name(),
}
if hi := pick.Hostinfo(); hi.Valid() {
if loc := hi.Location(); loc.Valid() {
res.Location = loc
}
}
return res, nil
}
// pickWeighted chooses the node with highest priority given a list of mullvad nodes.
func pickWeighted(candidates []tailcfg.NodeView) []tailcfg.NodeView {
maxWeight := 0
best := make([]tailcfg.NodeView, 0, 1)
for _, c := range candidates {
hi := c.Hostinfo()
if !hi.Valid() {
continue
}
loc := hi.Location()
if !loc.Valid() || loc.Priority() < maxWeight {
continue
}
if maxWeight != loc.Priority() {
best = best[:0]
}
maxWeight = loc.Priority()
best = append(best, c)
}
return best
}
// randomRegion is a selectRegionFunc that selects a uniformly random region.
func randomRegion(regions views.Slice[int]) int {
return regions.At(rand.IntN(regions.Len()))
}
// randomNode is a selectNodeFunc that will return the node matching prefer if
// present, otherwise a uniformly random node will be selected.
func randomNode(nodes views.Slice[tailcfg.NodeView], prefer tailcfg.StableNodeID) tailcfg.NodeView {
if !prefer.IsZero() {
for i := range nodes.Len() {
nv := nodes.At(i)
if nv.StableID() == prefer {
return nv
}
}
}
return nodes.At(rand.IntN(nodes.Len()))
}
// minLatencyDERPRegion returns the region with the lowest latency value given the last netcheck report.
// If there are no latency values, it returns 0.
func minLatencyDERPRegion(regions []int, report *netcheck.Report) int {
min := slices.MinFunc(regions, func(i, j int) int {
const largeDuration time.Duration = math.MaxInt64
iLatency, ok := report.RegionLatency[i]
if !ok {
iLatency = largeDuration
}
jLatency, ok := report.RegionLatency[j]
if !ok {
jLatency = largeDuration
}
if c := cmp.Compare(iLatency, jLatency); c != 0 {
return c
}
return cmp.Compare(i, j)
})
latency, ok := report.RegionLatency[min]
if !ok || latency == 0 {
return 0
} else {
return min
}
}
// longLatDistance returns an estimated distance given the geographic coordinates of two locations, in degrees.
// The coordinates are separated into four separate float64 values.
// Value is returned in meters.
func longLatDistance(fromLat, fromLong, toLat, toLong float64) float64 {
const toRadians = math.Pi / 180
diffLat := (fromLat - toLat) * toRadians
diffLong := (fromLong - toLong) * toRadians
lat1 := fromLat * toRadians
lat2 := toLat * toRadians
a := math.Pow(math.Sin(diffLat/2), 2) + math.Cos(lat1)*math.Cos(lat2)*math.Pow(math.Sin(diffLong/2), 2)
const earthRadiusMeters = 6371000
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
return earthRadiusMeters * c
}
// makeRendezvousHasher returns a function that hashes a node ID to a uint64.
// https://en.wikipedia.org/wiki/Rendezvous_hashing
func makeRendezvousHasher(seed tailcfg.NodeID) func(tailcfg.NodeID) uint64 {
en := binary.BigEndian
return func(n tailcfg.NodeID) uint64 {
var b [16]byte
en.PutUint64(b[:], uint64(seed))
en.PutUint64(b[8:], uint64(n))
v := sha256.Sum256(b[:])
return en.Uint64(v[:])
}
}
const (
// unresolvedExitNodeID is a special [tailcfg.StableNodeID] value
// used as an exit node ID to install a blackhole route, preventing
// accidental non-exit-node usage until the [ipn.ExitNodeExpression]
// is evaluated and an actual exit node is selected.
//
// We use "auto:any" for compatibility with older, pre-[ipn.ExitNodeExpression]
// clients that have been using "auto:any" for this purpose for a long time.
unresolvedExitNodeID tailcfg.StableNodeID = "auto:any"
)
func isAllowedAutoExitNodeID(polc policyclient.Client, exitNodeID tailcfg.StableNodeID) bool {
if exitNodeID == "" {
return false // an exit node is required
}
if nodes, _ := polc.GetStringArray(pkey.AllowedSuggestedExitNodes, nil); nodes != nil {
return slices.Contains(nodes, string(exitNodeID))
}
return true // no policy configured; allow all exit nodes
}
// srcIPHasCapForFilter is called by the packet filter when evaluating firewall
// rules that require a source IP to have a certain node capability.
//
// TODO(bradfitz): optimize this later if/when it matters.
// TODO(nickkhyl): move this into [nodeBackend] along with [LocalBackend.updateFilterLocked].
func (b *LocalBackend) srcIPHasCapForFilter(srcIP netip.Addr, cap tailcfg.NodeCapability) bool {
if cap == "" {
// Shouldn't happen, but just in case.
// But the empty cap also shouldn't be found in Node.CapMap.
return false
}
cn := b.currentNode()
nodeID, ok := cn.NodeByAddr(srcIP)
if !ok {
return false
}
n, ok := cn.NodeByID(nodeID)
if !ok {
return false
}
return n.HasCap(cap)
}
// maybeUsernameOf returns the actor's username if the actor
// is non-nil and its username can be resolved.
func maybeUsernameOf(actor ipnauth.Actor) string {
var username string
if actor != nil {
username, _ = actor.Username()
}
return username
}
var (
metricCurrentWatchIPNBus = clientmetric.NewGauge("localbackend_current_watch_ipn_bus")
metricIPForwardingCheckError = clientmetric.NewCounter("localbackend_ip_forwarding_check_error")
)
func (b *LocalBackend) stateEncrypted() opt.Bool {
switch runtime.GOOS {
case "android", "ios":
return opt.NewBool(true)
case "darwin":
switch {
case version.IsMacAppStore():
return opt.NewBool(true)
case version.IsMacSysExt():
sp, _ := b.polc.GetBoolean(pkey.EncryptState, true)
return opt.NewBool(sp)
default:
// Probably self-compiled tailscaled, we don't use the Keychain
// there.
return opt.NewBool(false)
}
default:
_, ok := b.store.(ipn.EncryptedStateStore)
return opt.NewBool(ok)
}
}
|