summaryrefslogtreecommitdiffhomepage
path: root/wgengine/router/router_linux_test.go
blob: b6a5a1ac04753da04f687153692488d479f2cbd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause

package router

import (
	"errors"
	"fmt"
	"math/rand"
	"net/netip"
	"os"
	"reflect"
	"regexp"
	"slices"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/tailscale/netlink"
	"github.com/tailscale/wireguard-go/tun"
	"go4.org/netipx"
	"tailscale.com/health"
	"tailscale.com/net/netmon"
	"tailscale.com/net/tsaddr"
	"tailscale.com/tstest"
	"tailscale.com/types/logger"
	"tailscale.com/util/eventbus"
	"tailscale.com/util/eventbus/eventbustest"
	"tailscale.com/util/linuxfw"
	"tailscale.com/version/distro"
)

func TestRouterStates(t *testing.T) {
	basic := `
ip rule add -4 pref 5210 fwmark 0x80000/0xff0000 table main
ip rule add -4 pref 5230 fwmark 0x80000/0xff0000 table default
ip rule add -4 pref 5250 fwmark 0x80000/0xff0000 type unreachable
ip rule add -4 pref 5270 table 52
ip rule add -6 pref 5210 fwmark 0x80000/0xff0000 table main
ip rule add -6 pref 5230 fwmark 0x80000/0xff0000 table default
ip rule add -6 pref 5250 fwmark 0x80000/0xff0000 type unreachable
ip rule add -6 pref 5270 table 52
`
	states := []struct {
		name string
		in   *Config
		want string
	}{
		{
			name: "no config",
			in:   nil,
			want: `
up` + basic,
		},
		{
			name: "local addr only",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.103/10"),
				NetfilterMode: netfilterOff,
			},
			want: `
up
ip addr add 100.101.102.103/10 dev tailscale0` + basic,
		},

		{
			name: "addr and routes",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.103/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "192.168.16.0/24"),
				NetfilterMode: netfilterOff,
			},
			want: `
up
ip addr add 100.101.102.103/10 dev tailscale0
ip route add 100.100.100.100/32 dev tailscale0 table 52
ip route add 192.168.16.0/24 dev tailscale0 table 52` + basic,
		},

		{
			name: "addr and routes and subnet routes",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.103/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "192.168.16.0/24"),
				SubnetRoutes:  mustCIDRs("200.0.0.0/8"),
				NetfilterMode: netfilterOff,
			},
			want: `
up
ip addr add 100.101.102.103/10 dev tailscale0
ip route add 100.100.100.100/32 dev tailscale0 table 52
ip route add 192.168.16.0/24 dev tailscale0 table 52` + basic,
		},

		{
			name: "addr and routes and subnet routes with netfilter",
			in: &Config{
				LocalAddrs:        mustCIDRs("100.101.102.104/10"),
				Routes:            mustCIDRs("100.100.100.100/32", "10.0.0.0/8"),
				SubnetRoutes:      mustCIDRs("200.0.0.0/8"),
				SNATSubnetRoutes:  true,
				StatefulFiltering: true,
				NetfilterMode:     netfilterOn,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 10.0.0.0/8 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52` + basic +
				`v4/filter/FORWARD -j ts-forward
v4/filter/INPUT -j ts-input
v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -m conntrack ! --ctstate ESTABLISHED,RELATED -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v4/nat/POSTROUTING -j ts-postrouting
v4/nat/ts-postrouting -m mark --mark 0x40000/0xff0000 -j MASQUERADE
v6/filter/FORWARD -j ts-forward
v6/filter/INPUT -j ts-input
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -m conntrack ! --ctstate ESTABLISHED,RELATED -j DROP
v6/filter/ts-forward -o tailscale0 -j ACCEPT
v6/nat/POSTROUTING -j ts-postrouting
v6/nat/ts-postrouting -m mark --mark 0x40000/0xff0000 -j MASQUERADE
`,
		},
		{
			name: "addr and routes and subnet routes with netfilter but no stateful filtering",
			in: &Config{
				LocalAddrs:        mustCIDRs("100.101.102.104/10"),
				Routes:            mustCIDRs("100.100.100.100/32", "10.0.0.0/8"),
				SubnetRoutes:      mustCIDRs("200.0.0.0/8"),
				SNATSubnetRoutes:  true,
				StatefulFiltering: false,
				NetfilterMode:     netfilterOn,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 10.0.0.0/8 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52` + basic +
				`v4/filter/FORWARD -j ts-forward
v4/filter/INPUT -j ts-input
v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v4/nat/POSTROUTING -j ts-postrouting
v4/nat/ts-postrouting -m mark --mark 0x40000/0xff0000 -j MASQUERADE
v6/filter/FORWARD -j ts-forward
v6/filter/INPUT -j ts-input
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -j ACCEPT
v6/nat/POSTROUTING -j ts-postrouting
v6/nat/ts-postrouting -m mark --mark 0x40000/0xff0000 -j MASQUERADE
`,
		},
		{
			name: "addr and routes with netfilter",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.104/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "10.0.0.0/8"),
				NetfilterMode: netfilterOn,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 10.0.0.0/8 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52` + basic +
				`v4/filter/FORWARD -j ts-forward
v4/filter/INPUT -j ts-input
v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v4/nat/POSTROUTING -j ts-postrouting
v6/filter/FORWARD -j ts-forward
v6/filter/INPUT -j ts-input
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -j ACCEPT
v6/nat/POSTROUTING -j ts-postrouting
`,
		},

		{
			name: "addr and routes and subnet routes with netfilter but no SNAT",
			in: &Config{
				LocalAddrs:       mustCIDRs("100.101.102.104/10"),
				Routes:           mustCIDRs("100.100.100.100/32", "10.0.0.0/8"),
				SubnetRoutes:     mustCIDRs("200.0.0.0/8"),
				SNATSubnetRoutes: false,
				NetfilterMode:    netfilterOn,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 10.0.0.0/8 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52` + basic +
				`v4/filter/FORWARD -j ts-forward
v4/filter/INPUT -j ts-input
v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v4/nat/POSTROUTING -j ts-postrouting
v6/filter/FORWARD -j ts-forward
v6/filter/INPUT -j ts-input
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -j ACCEPT
v6/nat/POSTROUTING -j ts-postrouting
`,
		},
		{
			name: "addr and routes with netfilter",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.104/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "10.0.0.0/8"),
				NetfilterMode: netfilterOn,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 10.0.0.0/8 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52` + basic +
				`v4/filter/FORWARD -j ts-forward
v4/filter/INPUT -j ts-input
v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v4/nat/POSTROUTING -j ts-postrouting
v6/filter/FORWARD -j ts-forward
v6/filter/INPUT -j ts-input
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -j ACCEPT
v6/nat/POSTROUTING -j ts-postrouting
`,
		},

		{
			name: "addr and routes with half netfilter",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.104/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "10.0.0.0/8"),
				NetfilterMode: netfilterNoDivert,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 10.0.0.0/8 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52` + basic +
				`v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -j ACCEPT
`,
		},
		{
			name: "addr and routes with netfilter2",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.104/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "10.0.0.0/8"),
				NetfilterMode: netfilterOn,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 10.0.0.0/8 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52` + basic +
				`v4/filter/FORWARD -j ts-forward
v4/filter/INPUT -j ts-input
v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v4/nat/POSTROUTING -j ts-postrouting
v6/filter/FORWARD -j ts-forward
v6/filter/INPUT -j ts-input
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -j ACCEPT
v6/nat/POSTROUTING -j ts-postrouting
`,
		},
		{
			name: "addr, routes, and local routes with netfilter",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.104/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "0.0.0.0/0"),
				LocalRoutes:   mustCIDRs("10.0.0.0/8"),
				NetfilterMode: netfilterOn,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 0.0.0.0/0 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52
ip route add throw 10.0.0.0/8 table 52` + basic +
				`v4/filter/FORWARD -j ts-forward
v4/filter/INPUT -j ts-input
v4/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v4/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v4/filter/ts-forward -o tailscale0 -s 100.64.0.0/10 -j DROP
v4/filter/ts-forward -o tailscale0 -j ACCEPT
v4/filter/ts-input -i lo -s 100.101.102.104 -j ACCEPT
v4/filter/ts-input ! -i tailscale0 -s 100.115.92.0/23 -j RETURN
v4/filter/ts-input ! -i tailscale0 -s 100.64.0.0/10 -j DROP
v4/nat/POSTROUTING -j ts-postrouting
v6/filter/FORWARD -j ts-forward
v6/filter/INPUT -j ts-input
v6/filter/ts-forward -i tailscale0 -j MARK --set-mark 0x40000/0xff0000
v6/filter/ts-forward -m mark --mark 0x40000/0xff0000 -j ACCEPT
v6/filter/ts-forward -o tailscale0 -j ACCEPT
v6/nat/POSTROUTING -j ts-postrouting
`,
		},
		{
			name: "addr, routes, and local routes with no netfilter",
			in: &Config{
				LocalAddrs:    mustCIDRs("100.101.102.104/10"),
				Routes:        mustCIDRs("100.100.100.100/32", "0.0.0.0/0"),
				LocalRoutes:   mustCIDRs("10.0.0.0/8", "192.168.0.0/24"),
				NetfilterMode: netfilterOff,
			},
			want: `
up
ip addr add 100.101.102.104/10 dev tailscale0
ip route add 0.0.0.0/0 dev tailscale0 table 52
ip route add 100.100.100.100/32 dev tailscale0 table 52
ip route add throw 10.0.0.0/8 table 52
ip route add throw 192.168.0.0/24 table 52` + basic,
		},
	}

	bus := eventbus.New()
	defer bus.Close()
	mon, err := netmon.New(bus, logger.Discard)
	if err != nil {
		t.Fatal(err)
	}
	mon.Start()
	defer mon.Close()

	fake := NewFakeOS(t)
	ht := new(health.Tracker)
	router, err := newUserspaceRouterAdvanced(t.Logf, "tailscale0", mon, fake, ht, bus)
	router.(*linuxRouter).nfr = fake.nfr
	if err != nil {
		t.Fatalf("failed to create router: %v", err)
	}
	if err := router.Up(); err != nil {
		t.Fatalf("failed to up router: %v", err)
	}

	testState := func(t *testing.T, i int) {
		t.Helper()
		if err := router.Set(states[i].in); err != nil {
			t.Fatalf("failed to set router config: %v", err)
		}
		got := fake.String()
		want := adjustFwmask(t, strings.TrimSpace(states[i].want))
		if diff := cmp.Diff(got, want); diff != "" {
			t.Fatalf("unexpected OS state (-got+want):\n%s", diff)
		}
	}

	for i, state := range states {
		t.Run(state.name, func(t *testing.T) { testState(t, i) })
	}

	// Cycle through a bunch of states in pseudorandom order, to
	// verify that we transition cleanly from state to state no matter
	// the order.
	for randRun := 0; randRun < 5*len(states); randRun++ {
		i := rand.Intn(len(states))
		state := states[i]
		t.Run(state.name, func(t *testing.T) { testState(t, i) })
	}
}

type fakeIPTablesRunner struct {
	t    *testing.T
	ipt4 map[string][]string
	ipt6 map[string][]string
	// we always assume ipv6 and ipv6 nat are enabled when testing
}

func newIPTablesRunner(t *testing.T) linuxfw.NetfilterRunner {
	return &fakeIPTablesRunner{
		t: t,
		ipt4: map[string][]string{
			"filter/INPUT":    nil,
			"filter/OUTPUT":   nil,
			"filter/FORWARD":  nil,
			"nat/PREROUTING":  nil,
			"nat/OUTPUT":      nil,
			"nat/POSTROUTING": nil,
		},
		ipt6: map[string][]string{
			"filter/INPUT":    nil,
			"filter/OUTPUT":   nil,
			"filter/FORWARD":  nil,
			"nat/PREROUTING":  nil,
			"nat/OUTPUT":      nil,
			"nat/POSTROUTING": nil,
		},
	}
}

func insertRule(n *fakeIPTablesRunner, curIPT map[string][]string, chain, newRule string) error {
	// Get current rules for filter/ts-input chain with according IP version
	curTSInputRules, ok := curIPT[chain]
	if !ok {
		n.t.Fatalf("no %s chain exists", chain)
		return fmt.Errorf("no %s chain exists", chain)
	}

	// Add new rule to top of filter/ts-input
	curTSInputRules = append(curTSInputRules, "")
	copy(curTSInputRules[1:], curTSInputRules)
	curTSInputRules[0] = newRule
	curIPT[chain] = curTSInputRules
	return nil
}

func insertRuleAt(n *fakeIPTablesRunner, curIPT map[string][]string, chain string, pos int, newRule string) {
	rules, ok := curIPT[chain]
	if !ok {
		n.t.Fatalf("no %s chain exists", chain)
	}

	// If the given position is after the end of the chain, error.
	if pos > len(rules) {
		n.t.Fatalf("position %d > len(chain %s) %d", pos, chain, len(chain))
	}

	// Insert the rule at the given position
	rules = slices.Insert(rules, pos, newRule)
	curIPT[chain] = rules
}

func appendRule(n *fakeIPTablesRunner, curIPT map[string][]string, chain, newRule string) error {
	// Get current rules for filter/ts-input chain with according IP version
	curTSInputRules, ok := curIPT[chain]
	if !ok {
		n.t.Fatalf("no %s chain exists", chain)
		return fmt.Errorf("no %s chain exists", chain)
	}

	// Add new rule to end of filter/ts-input
	curTSInputRules = append(curTSInputRules, newRule)
	curIPT[chain] = curTSInputRules
	return nil
}

func deleteRule(n *fakeIPTablesRunner, curIPT map[string][]string, chain, delRule string) error {
	// Get current rules for filter/ts-input chain with according IP version
	curTSInputRules, ok := curIPT[chain]
	if !ok {
		n.t.Fatalf("no %s chain exists", chain)
		return fmt.Errorf("no %s chain exists", chain)
	}

	// Remove rule from filter/ts-input
	for i, rule := range curTSInputRules {
		if rule == delRule {
			curTSInputRules = append(curTSInputRules[:i], curTSInputRules[i+1:]...)
			break
		}
	}
	curIPT[chain] = curTSInputRules
	return nil
}

func (n *fakeIPTablesRunner) AddLoopbackRule(addr netip.Addr) error {
	curIPT := n.ipt4
	if addr.Is6() {
		curIPT = n.ipt6
	}
	newRule := fmt.Sprintf("-i lo -s %s -j ACCEPT", addr.String())

	return insertRule(n, curIPT, "filter/ts-input", newRule)
}

func (n *fakeIPTablesRunner) AddBase(tunname string) error {
	if err := n.addBase4(tunname); err != nil {
		return err
	}
	if n.HasIPV6() {
		if err := n.addBase6(tunname); err != nil {
			return err
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) AddDNATRule(origDst, dst netip.Addr) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) DNATWithLoadBalancer(netip.Addr, []netip.Addr) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) EnsureSNATForDst(src, dst netip.Addr) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) DNATNonTailscaleTraffic(exemptInterface string, dst netip.Addr) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) EnsurePortMapRuleForSvc(svc, tun string, targetIP netip.Addr, pm linuxfw.PortMap) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) DeletePortMapRuleForSvc(svc, tun string, targetIP netip.Addr, pm linuxfw.PortMap) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) DeleteSvc(svc, tun string, targetIPs []netip.Addr, pm []linuxfw.PortMap) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) ClampMSSToPMTU(tun string, addr netip.Addr) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) EnsureDNATRuleForSvc(svcName string, origDst, dst netip.Addr) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) DeleteDNATRuleForSvc(svcName string, origDst, dst netip.Addr) error {
	return errors.New("not implemented")
}

func (n *fakeIPTablesRunner) addBase4(tunname string) error {
	curIPT := n.ipt4
	newRules := []struct{ chain, rule string }{
		{"filter/ts-input", fmt.Sprintf("! -i %s -s %s -j RETURN", tunname, tsaddr.ChromeOSVMRange().String())},
		{"filter/ts-input", fmt.Sprintf("! -i %s -s %s -j DROP", tunname, tsaddr.CGNATRange().String())},
		{"filter/ts-forward", fmt.Sprintf("-i %s -j MARK --set-mark %s/%s", tunname, linuxfw.TailscaleSubnetRouteMark, linuxfw.TailscaleFwmarkMask)},
		{"filter/ts-forward", fmt.Sprintf("-m mark --mark %s/%s -j ACCEPT", linuxfw.TailscaleSubnetRouteMark, linuxfw.TailscaleFwmarkMask)},
		{"filter/ts-forward", fmt.Sprintf("-o %s -s %s -j DROP", tunname, tsaddr.CGNATRange().String())},
		{"filter/ts-forward", fmt.Sprintf("-o %s -j ACCEPT", tunname)},
	}
	for _, rule := range newRules {
		if err := appendRule(n, curIPT, rule.chain, rule.rule); err != nil {
			return fmt.Errorf("add rule %q to chain %q: %w", rule.rule, rule.chain, err)
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) addBase6(tunname string) error {
	curIPT := n.ipt6
	newRules := []struct{ chain, rule string }{
		{"filter/ts-forward", fmt.Sprintf("-i %s -j MARK --set-mark %s/%s", tunname, linuxfw.TailscaleSubnetRouteMark, linuxfw.TailscaleFwmarkMask)},
		{"filter/ts-forward", fmt.Sprintf("-m mark --mark %s/%s -j ACCEPT", linuxfw.TailscaleSubnetRouteMark, linuxfw.TailscaleFwmarkMask)},
		{"filter/ts-forward", fmt.Sprintf("-o %s -j ACCEPT", tunname)},
	}
	for _, rule := range newRules {
		if err := appendRule(n, curIPT, rule.chain, rule.rule); err != nil {
			return fmt.Errorf("add rule %q to chain %q: %w", rule.rule, rule.chain, err)
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) DelLoopbackRule(addr netip.Addr) error {
	curIPT := n.ipt4
	if addr.Is6() {
		curIPT = n.ipt6
	}

	delRule := fmt.Sprintf("-i lo -s %s -j ACCEPT", addr.String())

	return deleteRule(n, curIPT, "filter/ts-input", delRule)
}

func (n *fakeIPTablesRunner) AddHooks() error {
	newRules := []struct{ chain, rule string }{
		{"filter/INPUT", "-j ts-input"},
		{"filter/FORWARD", "-j ts-forward"},
		{"nat/POSTROUTING", "-j ts-postrouting"},
	}
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		for _, r := range newRules {
			if err := insertRule(n, ipt, r.chain, r.rule); err != nil {
				return err
			}
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) DelHooks(logf logger.Logf) error {
	delRules := []struct{ chain, rule string }{
		{"filter/INPUT", "-j ts-input"},
		{"filter/FORWARD", "-j ts-forward"},
		{"nat/POSTROUTING", "-j ts-postrouting"},
	}
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		for _, r := range delRules {
			if err := deleteRule(n, ipt, r.chain, r.rule); err != nil {
				return err
			}
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) AddChains() error {
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		for _, chain := range []string{"filter/ts-input", "filter/ts-forward", "nat/ts-postrouting"} {
			ipt[chain] = nil
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) DelChains() error {
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		for chain := range ipt {
			if strings.HasPrefix(chain, "filter/ts-") || strings.HasPrefix(chain, "nat/ts-") {
				delete(ipt, chain)
			}
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) DelBase() error {
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		for _, chain := range []string{"filter/ts-input", "filter/ts-forward", "nat/ts-postrouting"} {
			ipt[chain] = nil
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) AddSNATRule() error {
	newRule := fmt.Sprintf("-m mark --mark %s/%s -j MASQUERADE", linuxfw.TailscaleSubnetRouteMark, linuxfw.TailscaleFwmarkMask)
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		if err := appendRule(n, ipt, "nat/ts-postrouting", newRule); err != nil {
			return err
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) DelSNATRule() error {
	delRule := fmt.Sprintf("-m mark --mark %s/%s -j MASQUERADE", linuxfw.TailscaleSubnetRouteMark, linuxfw.TailscaleFwmarkMask)
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		if err := deleteRule(n, ipt, "nat/ts-postrouting", delRule); err != nil {
			return err
		}
	}
	return nil
}

func (n *fakeIPTablesRunner) AddStatefulRule(tunname string) error {
	newRule := fmt.Sprintf("-o %s -m conntrack ! --ctstate ESTABLISHED,RELATED -j DROP", tunname)
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		// Mimic the real runner and insert after the 'accept all' rule
		wantRule := fmt.Sprintf("-o %s -j ACCEPT", tunname)

		const chain = "filter/ts-forward"
		pos := slices.Index(ipt[chain], wantRule)
		if pos < 0 {
			n.t.Fatalf("no rule %q in chain %s", wantRule, chain)
		}

		insertRuleAt(n, ipt, chain, pos, newRule)
	}
	return nil
}

func (n *fakeIPTablesRunner) DelStatefulRule(tunname string) error {
	delRule := fmt.Sprintf("-o %s -m conntrack ! --ctstate ESTABLISHED,RELATED -j DROP", tunname)
	for _, ipt := range []map[string][]string{n.ipt4, n.ipt6} {
		if err := deleteRule(n, ipt, "filter/ts-forward", delRule); err != nil {
			return err
		}
	}
	return nil
}

// buildMagicsockPortRule builds a fake rule to use in AddMagicsockPortRule and
// DelMagicsockPortRule below.
func buildMagicsockPortRule(port uint16) string {
	return fmt.Sprintf("-p udp --dport %v -j ACCEPT", port)
}

// AddMagicsockPortRule implements the NetfilterRunner interface, but stores
// rules in fakeIPTablesRunner's internal maps rather than actually calling out
// to iptables. This is mainly to test the linux router implementation.
func (n *fakeIPTablesRunner) AddMagicsockPortRule(port uint16, network string) error {
	var ipt map[string][]string
	switch network {
	case "udp4":
		ipt = n.ipt4
	case "udp6":
		ipt = n.ipt6
	default:
		return fmt.Errorf("unsupported network %s", network)
	}

	rule := buildMagicsockPortRule(port)

	if err := appendRule(n, ipt, "filter/ts-input", rule); err != nil {
		return err
	}

	return nil
}

// DelMagicsockPortRule implements the NetfilterRunner interface, but removes
// rules from fakeIPTablesRunner's internal maps rather than actually calling
// out to iptables. This is mainly to test the linux router implementation.
func (n *fakeIPTablesRunner) DelMagicsockPortRule(port uint16, network string) error {
	var ipt map[string][]string
	switch network {
	case "udp4":
		ipt = n.ipt4
	case "udp6":
		ipt = n.ipt6
	default:
		return fmt.Errorf("unsupported network %s", network)
	}

	rule := buildMagicsockPortRule(port)

	if err := deleteRule(n, ipt, "filter/ts-input", rule); err != nil {
		return err
	}

	return nil
}

func (n *fakeIPTablesRunner) HasIPV6() bool       { return true }
func (n *fakeIPTablesRunner) HasIPV6NAT() bool    { return true }
func (n *fakeIPTablesRunner) HasIPV6Filter() bool { return true }

// fakeOS implements commandRunner and provides v4 and v6
// netfilterRunners, but captures changes without touching the OS.
type fakeOS struct {
	t      *testing.T
	up     bool
	ips    []string
	routes []string
	rules  []string
	// This test tests on the router level, so we will not bother
	// with using iptables or nftables, chose the simpler one.
	nfr linuxfw.NetfilterRunner
}

func NewFakeOS(t *testing.T) *fakeOS {
	return &fakeOS{
		t:   t,
		nfr: newIPTablesRunner(t),
	}
}

var errExec = errors.New("execution failed")

func (o *fakeOS) String() string {
	var b strings.Builder
	if o.up {
		b.WriteString("up\n")
	} else {
		b.WriteString("down\n")
	}

	for _, ip := range o.ips {
		fmt.Fprintf(&b, "ip addr add %s\n", ip)
	}

	for _, route := range o.routes {
		fmt.Fprintf(&b, "ip route add %s\n", route)
	}

	for _, rule := range o.rules {
		fmt.Fprintf(&b, "ip rule add %s\n", rule)
	}

	var chains []string
	for chain := range o.nfr.(*fakeIPTablesRunner).ipt4 {
		chains = append(chains, chain)
	}
	sort.Strings(chains)
	for _, chain := range chains {
		for _, rule := range o.nfr.(*fakeIPTablesRunner).ipt4[chain] {
			fmt.Fprintf(&b, "v4/%s %s\n", chain, rule)
		}
	}

	chains = nil
	for chain := range o.nfr.(*fakeIPTablesRunner).ipt6 {
		chains = append(chains, chain)
	}
	sort.Strings(chains)
	for _, chain := range chains {
		for _, rule := range o.nfr.(*fakeIPTablesRunner).ipt6[chain] {
			fmt.Fprintf(&b, "v6/%s %s\n", chain, rule)
		}
	}

	return b.String()[:len(b.String())-1]
}

func (o *fakeOS) run(args ...string) error {
	unexpected := func() error {
		o.t.Errorf("unexpected invocation %q", strings.Join(args, " "))
		return errors.New("unrecognized invocation")
	}
	if args[0] != "ip" {
		return unexpected()
	}

	if len(args) == 2 && args[1] == "rule" {
		// naked invocation of `ip rule` is a feature test. Return
		// successfully.
		return nil
	}

	family := ""
	rest := strings.Join(args[3:], " ")
	if args[1] == "-4" || args[1] == "-6" {
		family = args[1]
		copy(args[1:], args[2:])
		args = args[:len(args)-1]
		rest = family + " " + strings.Join(args[3:], " ")
	}

	var l *[]string
	switch args[1] {
	case "link":
		got := strings.Join(args[2:], " ")
		switch got {
		case "set dev tailscale0 up":
			o.up = true
		case "set dev tailscale0 down":
			o.up = false
		default:
			return unexpected()
		}
		return nil
	case "addr":
		l = &o.ips
	case "route":
		l = &o.routes
	case "rule":
		l = &o.rules
	default:
		return unexpected()
	}

	switch args[2] {
	case "add":
		for _, el := range *l {
			if el == rest {
				o.t.Errorf("can't add %q, already present", rest)
				return errors.New("already exists")
			}
		}
		*l = append(*l, rest)
		sort.Strings(*l)
	case "del":
		found := false
		for i, el := range *l {
			if el == rest {
				found = true
				*l = append((*l)[:i], (*l)[i+1:]...)
				break
			}
		}
		if !found {
			o.t.Logf("note: can't delete %q, not present", rest)
			// 'ip rule del' exits with code 2 when a row is
			// missing. We don't want to consider that an error,
			// for cleanup purposes.

			// TODO(apenwarr): this is a hack.
			// I'd like to return an exec.ExitError(2) here, but
			// I can't, because the ExitCode is implemented in
			// os.ProcessState, which is an opaque object I can't
			// instantiate or modify. Go's 75 levels of abstraction
			// between me and an 8-bit int are really paying off
			// here, as you can see.
			return errors.New("exitcode:2")
		}
	default:
		return unexpected()
	}

	return nil
}

func (o *fakeOS) output(args ...string) ([]byte, error) {
	want := "ip rule list priority 10000"
	got := strings.Join(args, " ")
	if got != want {
		o.t.Errorf("unexpected command that wants output: %v", got)
		return nil, errExec
	}

	var ret []string
	for _, rule := range o.rules {
		if strings.Contains(rule, "10000") {
			ret = append(ret, rule)
		}
	}
	return []byte(strings.Join(ret, "\n")), nil
}

var tunTestNum int64

func createTestTUN(t *testing.T) tun.Device {
	const minimalMTU = 1280
	tunName := fmt.Sprintf("tuntest%d", atomic.AddInt64(&tunTestNum, 1))
	tun, err := tun.CreateTUN(tunName, minimalMTU)
	if err != nil {
		t.Fatalf("CreateTUN(%q): %v", tunName, err)
	}
	return tun
}

type linuxTest struct {
	tun       tun.Device
	mon       *netmon.Monitor
	r         *linuxRouter
	logOutput tstest.MemLogger
}

func (lt *linuxTest) Close() error {
	if lt.tun != nil {
		lt.tun.Close()
	}
	if lt.mon != nil {
		lt.mon.Close()
	}
	return nil
}

func newLinuxRootTest(t *testing.T) (*linuxTest, *eventbus.Bus) {
	if os.Getuid() != 0 {
		t.Skip("test requires root")
	}

	lt := new(linuxTest)
	lt.tun = createTestTUN(t)

	logf := lt.logOutput.Logf

	bus := eventbustest.NewBus(t)

	mon, err := netmon.New(bus, logger.Discard)
	if err != nil {
		lt.Close()
		t.Fatal(err)
	}
	mon.Start()
	lt.mon = mon

	r, err := newUserspaceRouter(logf, lt.tun, mon, nil, bus)
	if err != nil {
		lt.Close()
		t.Fatal(err)
	}
	lr := r.(*linuxRouter)
	if err := lr.upInterface(); err != nil {
		lt.Close()
		t.Fatal(err)
	}
	lt.r = lr
	return lt, bus
}

func TestRuleDeletedEvent(t *testing.T) {
	fake := NewFakeOS(t)
	lt, bus := newLinuxRootTest(t)
	lt.r.nfr = fake.nfr
	defer lt.Close()
	event := netmon.RuleDeleted{
		Table:    52,
		Priority: 5210,
	}
	tw := eventbustest.NewWatcher(t, bus)

	t.Logf("Value before: %t", lt.r.ruleRestorePending.Load())
	if lt.r.ruleRestorePending.Load() {
		t.Errorf("rule deletion already ongoing")
	}
	injector := eventbustest.NewInjector(t, bus)
	eventbustest.Inject(injector, event)
	eventbustest.Expect(tw, eventbustest.Type[AddIPRules]())
}

func TestDelRouteIdempotent(t *testing.T) {
	lt, _ := newLinuxRootTest(t)
	defer lt.Close()

	for _, s := range []string{
		"192.0.2.0/24",  // RFC 5737
		"2001:DB8::/32", // RFC 3849
	} {
		cidr := netip.MustParsePrefix(s)
		if err := lt.r.addRoute(cidr); err != nil {
			t.Error(err)
			continue
		}
		for i := range 2 {
			if err := lt.r.delRoute(cidr); err != nil {
				t.Errorf("delRoute(i=%d): %v", i, err)
			}
		}
	}

	if t.Failed() {
		out := lt.logOutput.String()
		t.Logf("Log output:\n%s", out)
	}
}

func TestAddRemoveRules(t *testing.T) {
	lt, _ := newLinuxRootTest(t)
	defer lt.Close()
	r := lt.r

	step := func(name string, f func() error) {
		t.Logf("Doing %v ...", name)
		if err := f(); err != nil {
			t.Fatalf("%s: %v", name, err)
		}
		rules, err := netlink.RuleList(netlink.FAMILY_ALL)
		if err != nil {
			t.Fatal(err)
		}
		for _, r := range rules {
			if r.Priority >= 5000 && r.Priority <= 5999 {
				t.Logf("Rule: %+v", r)
			}
		}
	}

	step("init_del_and_add", r.addIPRules)
	step("dup_add", r.justAddIPRules)
	step("del", r.delIPRules)
	step("dup_del", r.delIPRules)
}

func TestDebugListLinks(t *testing.T) {
	links, err := netlink.LinkList()
	if err != nil {
		t.Fatal(err)
	}
	for _, ln := range links {
		t.Logf("Link: %+v", ln)
	}
}

func TestDebugListRoutes(t *testing.T) {
	// We need to pass a non-nil route to RouteListFiltered, along
	// with the netlink.RT_FILTER_TABLE bit set in the filter
	// mask, otherwise it ignores non-main routes.
	filter := &netlink.Route{}
	routes, err := netlink.RouteListFiltered(netlink.FAMILY_ALL, filter, netlink.RT_FILTER_TABLE)
	if err != nil {
		t.Fatal(err)
	}
	for _, r := range routes {
		t.Logf("Route: %+v", r)
	}
}

var famName = map[int]string{
	netlink.FAMILY_ALL: "all",
	netlink.FAMILY_V4:  "v4",
	netlink.FAMILY_V6:  "v6",
}

func TestDebugListRules(t *testing.T) {
	for _, fam := range []int{netlink.FAMILY_V4, netlink.FAMILY_V6, netlink.FAMILY_ALL} {
		t.Run(famName[fam], func(t *testing.T) {
			rules, err := netlink.RuleList(fam)
			if err != nil {
				t.Skipf("skip; RuleList fails with: %v", err)
			}
			for _, r := range rules {
				t.Logf("Rule: %+v", r)
			}
		})
	}
}

func TestCheckIPRuleSupportsV6(t *testing.T) {
	err := linuxfw.CheckIPRuleSupportsV6(t.Logf)
	if err != nil && os.Getuid() != 0 {
		t.Skipf("skipping, error when not root: %v", err)
	}
	// Just log it. For interactive testing only.
	// Some machines running our tests might not have IPv6.
	t.Logf("Got: %v", err)
}

func TestBusyboxParseVersion(t *testing.T) {
	input := `BusyBox v1.34.1 (2022-09-01 16:10:29 UTC) multi-call binary.
BusyBox is copyrighted by many authors between 1998-2015.
Licensed under GPLv2. See source distribution for detailed
copyright notices.

Usage: busybox [function [arguments]...]
   or: busybox --list[-full]
   or: busybox --show SCRIPT
   or: busybox --install [-s] [DIR]
   or: function [arguments]...

	BusyBox is a multi-call binary that combines many common Unix
	utilities into a single executable.  Most people will create a
	link to busybox for each function they wish to use and BusyBox
	will act like whatever it was invoked as.
`

	v1, v2, v3, err := busyboxParseVersion(input)
	if err != nil {
		t.Fatalf("busyboxParseVersion() failed: %v", err)
	}

	if got, want := fmt.Sprintf("%d.%d.%d", v1, v2, v3), "1.34.1"; got != want {
		t.Errorf("version = %q, want %q", got, want)
	}
}

func TestCIDRDiff(t *testing.T) {
	pfx := func(p ...string) []netip.Prefix {
		var ret []netip.Prefix
		for _, s := range p {
			ret = append(ret, netip.MustParsePrefix(s))
		}
		return ret
	}
	tests := []struct {
		old     []netip.Prefix
		new     []netip.Prefix
		wantAdd []netip.Prefix
		wantDel []netip.Prefix
		final   []netip.Prefix
	}{
		{
			old:     nil,
			new:     pfx("1.1.1.1/32"),
			wantAdd: pfx("1.1.1.1/32"),
			final:   pfx("1.1.1.1/32"),
		},
		{
			old:   pfx("1.1.1.1/32"),
			new:   pfx("1.1.1.1/32"),
			final: pfx("1.1.1.1/32"),
		},
		{
			old:     pfx("1.1.1.1/32", "2.3.4.5/32"),
			new:     pfx("1.1.1.1/32"),
			wantDel: pfx("2.3.4.5/32"),
			final:   pfx("1.1.1.1/32"),
		},
		{
			old:     pfx("1.1.1.1/32", "2.3.4.5/32"),
			new:     pfx("1.0.0.0/32", "3.4.5.6/32"),
			wantDel: pfx("1.1.1.1/32", "2.3.4.5/32"),
			wantAdd: pfx("1.0.0.0/32", "3.4.5.6/32"),
			final:   pfx("1.0.0.0/32", "3.4.5.6/32"),
		},
	}
	for _, tc := range tests {
		om := make(map[netip.Prefix]bool)
		for _, p := range tc.old {
			om[p] = true
		}
		var added []netip.Prefix
		var deleted []netip.Prefix
		fm, err := cidrDiff("test", om, tc.new, func(p netip.Prefix) error {
			if len(deleted) > 0 {
				t.Error("delete called before add")
			}
			added = append(added, p)
			return nil
		}, func(p netip.Prefix) error {
			deleted = append(deleted, p)
			return nil
		}, t.Logf)
		if err != nil {
			t.Fatal(err)
		}
		slices.SortFunc(added, netipx.ComparePrefix)
		slices.SortFunc(deleted, netipx.ComparePrefix)
		if !reflect.DeepEqual(added, tc.wantAdd) {
			t.Errorf("added = %v, want %v", added, tc.wantAdd)
		}
		if !reflect.DeepEqual(deleted, tc.wantDel) {
			t.Errorf("deleted = %v, want %v", deleted, tc.wantDel)
		}

		// Check that the final state is correct.
		if len(fm) != len(tc.final) {
			t.Fatalf("final state = %v, want %v", fm, tc.final)
		}
		for _, p := range tc.final {
			if !fm[p] {
				t.Errorf("final state = %v, want %v", fm, tc.final)
			}
		}
	}
}

var (
	fwmaskSupported     bool
	fwmaskSupportedOnce sync.Once
	fwmaskAdjustRe      = regexp.MustCompile(`(?m)(fwmark 0x[0-9a-f]+)/0x[0-9a-f]+`)
)

// adjustFwmask removes the "/0xmask" string from fwmask stanzas if the
// installed 'ip' binary does not support that format.
func adjustFwmask(t *testing.T, s string) string {
	t.Helper()
	fwmaskSupportedOnce.Do(func() {
		fwmaskSupported, _ = ipCmdSupportsFwmask()
	})
	if fwmaskSupported {
		return s
	}

	return fwmaskAdjustRe.ReplaceAllString(s, "$1")
}

func TestIPRulesForUBNT(t *testing.T) {
	// Override the global getDistroFunc
	getDistroFunc = func() distro.Distro {
		return distro.UBNT
	}
	defer func() { getDistroFunc = distro.Get }() // Restore original after the test

	expected := ubntIPRules
	actual := ipRules()

	if len(expected) != len(actual) {
		t.Fatalf("Expected %d rules, got %d", len(expected), len(actual))
	}

	for i, rule := range expected {
		if rule != actual[i] {
			t.Errorf("Rule mismatch at index %d: expected %+v, got %+v", i, rule, actual[i])
		}
	}
}