File: opts.go

package info (click to toggle)
nats-server 2.10.27-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,332 kB
  • sloc: sh: 691; makefile: 3
file content (5710 lines) | stat: -rw-r--r-- 173,968 bytes parent folder | download
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
// Copyright 2012-2023 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package server

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"flag"
	"fmt"
	"math"
	"net"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"github.com/nats-io/jwt/v2"
	"github.com/nats-io/nats-server/v2/conf"
	"github.com/nats-io/nats-server/v2/server/certidp"
	"github.com/nats-io/nats-server/v2/server/certstore"
	"github.com/nats-io/nkeys"
)

var allowUnknownTopLevelField = int32(0)

// NoErrOnUnknownFields can be used to change the behavior the processing
// of a configuration file. By default, an error is reported if unknown
// fields are found. If `noError` is set to true, no error will be reported
// if top-level unknown fields are found.
func NoErrOnUnknownFields(noError bool) {
	var val int32
	if noError {
		val = int32(1)
	}
	atomic.StoreInt32(&allowUnknownTopLevelField, val)
}

// PinnedCertSet is a set of lower case hex-encoded sha256 of DER encoded SubjectPublicKeyInfo
type PinnedCertSet map[string]struct{}

// ClusterOpts are options for clusters.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type ClusterOpts struct {
	Name              string            `json:"-"`
	Host              string            `json:"addr,omitempty"`
	Port              int               `json:"cluster_port,omitempty"`
	Username          string            `json:"-"`
	Password          string            `json:"-"`
	AuthTimeout       float64           `json:"auth_timeout,omitempty"`
	Permissions       *RoutePermissions `json:"-"`
	TLSTimeout        float64           `json:"-"`
	TLSConfig         *tls.Config       `json:"-"`
	TLSMap            bool              `json:"-"`
	TLSCheckKnownURLs bool              `json:"-"`
	TLSPinnedCerts    PinnedCertSet     `json:"-"`
	ListenStr         string            `json:"-"`
	Advertise         string            `json:"-"`
	NoAdvertise       bool              `json:"-"`
	ConnectRetries    int               `json:"-"`
	PoolSize          int               `json:"-"`
	PinnedAccounts    []string          `json:"-"`
	Compression       CompressionOpts   `json:"-"`
	PingInterval      time.Duration     `json:"-"`
	MaxPingsOut       int               `json:"-"`

	// Not exported (used in tests)
	resolver netResolver
	// Snapshot of configured TLS options.
	tlsConfigOpts *TLSConfigOpts
}

// CompressionOpts defines the compression mode and optional configuration.
type CompressionOpts struct {
	Mode string
	// If `Mode` is set to CompressionS2Auto, RTTThresholds provides the
	// thresholds at which the compression level will go from
	// CompressionS2Uncompressed to CompressionS2Fast, CompressionS2Better
	// or CompressionS2Best. If a given level is not desired, specify 0
	// for this slot. For instance, the slice []{0, 10ms, 20ms} means that
	// for any RTT up to 10ms included the compression level will be
	// CompressionS2Fast, then from ]10ms..20ms], the level will be selected
	// as CompressionS2Better. Anything above 20ms will result in picking
	// the CompressionS2Best compression level.
	RTTThresholds []time.Duration
}

// GatewayOpts are options for gateways.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type GatewayOpts struct {
	Name              string               `json:"name"`
	Host              string               `json:"addr,omitempty"`
	Port              int                  `json:"port,omitempty"`
	Username          string               `json:"-"`
	Password          string               `json:"-"`
	AuthTimeout       float64              `json:"auth_timeout,omitempty"`
	TLSConfig         *tls.Config          `json:"-"`
	TLSTimeout        float64              `json:"tls_timeout,omitempty"`
	TLSMap            bool                 `json:"-"`
	TLSCheckKnownURLs bool                 `json:"-"`
	TLSPinnedCerts    PinnedCertSet        `json:"-"`
	Advertise         string               `json:"advertise,omitempty"`
	ConnectRetries    int                  `json:"connect_retries,omitempty"`
	Gateways          []*RemoteGatewayOpts `json:"gateways,omitempty"`
	RejectUnknown     bool                 `json:"reject_unknown,omitempty"` // config got renamed to reject_unknown_cluster

	// Not exported, for tests.
	resolver         netResolver
	sendQSubsBufSize int

	// Snapshot of configured TLS options.
	tlsConfigOpts *TLSConfigOpts
}

// RemoteGatewayOpts are options for connecting to a remote gateway
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type RemoteGatewayOpts struct {
	Name          string      `json:"name"`
	TLSConfig     *tls.Config `json:"-"`
	TLSTimeout    float64     `json:"tls_timeout,omitempty"`
	URLs          []*url.URL  `json:"urls,omitempty"`
	tlsConfigOpts *TLSConfigOpts
}

// LeafNodeOpts are options for a given server to accept leaf node connections and/or connect to a remote cluster.
type LeafNodeOpts struct {
	Host              string        `json:"addr,omitempty"`
	Port              int           `json:"port,omitempty"`
	Username          string        `json:"-"`
	Password          string        `json:"-"`
	Nkey              string        `json:"-"`
	Account           string        `json:"-"`
	Users             []*User       `json:"-"`
	AuthTimeout       float64       `json:"auth_timeout,omitempty"`
	TLSConfig         *tls.Config   `json:"-"`
	TLSTimeout        float64       `json:"tls_timeout,omitempty"`
	TLSMap            bool          `json:"-"`
	TLSPinnedCerts    PinnedCertSet `json:"-"`
	TLSHandshakeFirst bool          `json:"-"`
	Advertise         string        `json:"-"`
	NoAdvertise       bool          `json:"-"`
	ReconnectInterval time.Duration `json:"-"`

	// Compression options
	Compression CompressionOpts `json:"-"`

	// For solicited connections to other clusters/superclusters.
	Remotes []*RemoteLeafOpts `json:"remotes,omitempty"`

	// This is the minimum version that is accepted for remote connections.
	// Note that since the server version in the CONNECT protocol was added
	// only starting at v2.8.0, any version below that will be rejected
	// (since empty version string in CONNECT would fail the "version at
	// least" test).
	MinVersion string

	// Not exported, for tests.
	resolver    netResolver
	dialTimeout time.Duration
	connDelay   time.Duration

	// Snapshot of configured TLS options.
	tlsConfigOpts *TLSConfigOpts
}

// SignatureHandler is used to sign a nonce from the server while
// authenticating with Nkeys. The callback should sign the nonce and
// return the JWT and the raw signature.
type SignatureHandler func([]byte) (string, []byte, error)

// RemoteLeafOpts are options for connecting to a remote server as a leaf node.
type RemoteLeafOpts struct {
	LocalAccount      string           `json:"local_account,omitempty"`
	NoRandomize       bool             `json:"-"`
	URLs              []*url.URL       `json:"urls,omitempty"`
	Credentials       string           `json:"-"`
	Nkey              string           `json:"-"`
	SignatureCB       SignatureHandler `json:"-"`
	TLS               bool             `json:"-"`
	TLSConfig         *tls.Config      `json:"-"`
	TLSTimeout        float64          `json:"tls_timeout,omitempty"`
	TLSHandshakeFirst bool             `json:"-"`
	Hub               bool             `json:"hub,omitempty"`
	DenyImports       []string         `json:"-"`
	DenyExports       []string         `json:"-"`

	// FirstInfoTimeout is the amount of time the server will wait for the
	// initial INFO protocol from the remote server before closing the
	// connection.
	FirstInfoTimeout time.Duration `json:"-"`

	// Compression options for this remote. Each remote could have a different
	// setting and also be different from the LeafNode options.
	Compression CompressionOpts `json:"-"`

	// When an URL has the "ws" (or "wss") scheme, then the server will initiate the
	// connection as a websocket connection. By default, the websocket frames will be
	// masked (as if this server was a websocket client to the remote server). The
	// NoMasking option will change this behavior and will send umasked frames.
	Websocket struct {
		Compression bool `json:"-"`
		NoMasking   bool `json:"-"`
	}

	tlsConfigOpts *TLSConfigOpts

	// If we are clustered and our local account has JetStream, if apps are accessing
	// a stream or consumer leader through this LN and it gets dropped, the apps will
	// not be able to work. This tells the system to migrate the leaders away from this server.
	// This only changes leader for R>1 assets.
	JetStreamClusterMigrate bool `json:"jetstream_cluster_migrate,omitempty"`
}

type JSLimitOpts struct {
	MaxRequestBatch int
	MaxAckPending   int
	MaxHAAssets     int
	Duplicates      time.Duration
}

// AuthCallout option used to map external AuthN to NATS based AuthZ.
type AuthCallout struct {
	// Must be a public account Nkey.
	Issuer string
	// Account to be used for sending requests.
	Account string
	// Users that will bypass auth_callout and be used for the auth service itself.
	AuthUsers []string
	// XKey is a public xkey for the authorization service.
	// This will enable encryption for server requests and the authorization service responses.
	XKey string
}

// Options block for nats-server.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
type Options struct {
	ConfigFile                 string        `json:"-"`
	ServerName                 string        `json:"server_name"`
	Host                       string        `json:"addr"`
	Port                       int           `json:"port"`
	DontListen                 bool          `json:"dont_listen"`
	ClientAdvertise            string        `json:"-"`
	Trace                      bool          `json:"-"`
	Debug                      bool          `json:"-"`
	TraceVerbose               bool          `json:"-"`
	NoLog                      bool          `json:"-"`
	NoSigs                     bool          `json:"-"`
	NoSublistCache             bool          `json:"-"`
	NoHeaderSupport            bool          `json:"-"`
	DisableShortFirstPing      bool          `json:"-"`
	Logtime                    bool          `json:"-"`
	LogtimeUTC                 bool          `json:"-"`
	MaxConn                    int           `json:"max_connections"`
	MaxSubs                    int           `json:"max_subscriptions,omitempty"`
	MaxSubTokens               uint8         `json:"-"`
	Nkeys                      []*NkeyUser   `json:"-"`
	Users                      []*User       `json:"-"`
	Accounts                   []*Account    `json:"-"`
	NoAuthUser                 string        `json:"-"`
	SystemAccount              string        `json:"-"`
	NoSystemAccount            bool          `json:"-"`
	Username                   string        `json:"-"`
	Password                   string        `json:"-"`
	Authorization              string        `json:"-"`
	AuthCallout                *AuthCallout  `json:"-"`
	PingInterval               time.Duration `json:"ping_interval"`
	MaxPingsOut                int           `json:"ping_max"`
	HTTPHost                   string        `json:"http_host"`
	HTTPPort                   int           `json:"http_port"`
	HTTPBasePath               string        `json:"http_base_path"`
	HTTPSPort                  int           `json:"https_port"`
	AuthTimeout                float64       `json:"auth_timeout"`
	MaxControlLine             int32         `json:"max_control_line"`
	MaxPayload                 int32         `json:"max_payload"`
	MaxPending                 int64         `json:"max_pending"`
	NoFastProducerStall        bool          `json:"-"`
	Cluster                    ClusterOpts   `json:"cluster,omitempty"`
	Gateway                    GatewayOpts   `json:"gateway,omitempty"`
	LeafNode                   LeafNodeOpts  `json:"leaf,omitempty"`
	JetStream                  bool          `json:"jetstream"`
	JetStreamMaxMemory         int64         `json:"-"`
	JetStreamMaxStore          int64         `json:"-"`
	JetStreamDomain            string        `json:"-"`
	JetStreamExtHint           string        `json:"-"`
	JetStreamKey               string        `json:"-"`
	JetStreamOldKey            string        `json:"-"`
	JetStreamCipher            StoreCipher   `json:"-"`
	JetStreamUniqueTag         string
	JetStreamLimits            JSLimitOpts
	JetStreamMaxCatchup        int64
	JetStreamRequestQueueLimit int64
	StoreDir                   string            `json:"-"`
	SyncInterval               time.Duration     `json:"-"`
	SyncAlways                 bool              `json:"-"`
	JsAccDefaultDomain         map[string]string `json:"-"` // account to domain name mapping
	Websocket                  WebsocketOpts     `json:"-"`
	MQTT                       MQTTOpts          `json:"-"`
	ProfPort                   int               `json:"-"`
	ProfBlockRate              int               `json:"-"`
	PidFile                    string            `json:"-"`
	PortsFileDir               string            `json:"-"`
	LogFile                    string            `json:"-"`
	LogSizeLimit               int64             `json:"-"`
	LogMaxFiles                int64             `json:"-"`
	Syslog                     bool              `json:"-"`
	RemoteSyslog               string            `json:"-"`
	Routes                     []*url.URL        `json:"-"`
	RoutesStr                  string            `json:"-"`
	TLSTimeout                 float64           `json:"tls_timeout"`
	TLS                        bool              `json:"-"`
	TLSVerify                  bool              `json:"-"`
	TLSMap                     bool              `json:"-"`
	TLSCert                    string            `json:"-"`
	TLSKey                     string            `json:"-"`
	TLSCaCert                  string            `json:"-"`
	TLSConfig                  *tls.Config       `json:"-"`
	TLSPinnedCerts             PinnedCertSet     `json:"-"`
	TLSRateLimit               int64             `json:"-"`
	// When set to true, the server will perform the TLS handshake before
	// sending the INFO protocol. For clients that are not configured
	// with a similar option, their connection will fail with some sort
	// of timeout or EOF error since they are expecting to receive an
	// INFO protocol first.
	TLSHandshakeFirst bool `json:"-"`
	// If TLSHandshakeFirst is true and this value is strictly positive,
	// the server will wait for that amount of time for the TLS handshake
	// to start before falling back to previous behavior of sending the
	// INFO protocol first. It allows for a mix of newer clients that can
	// require a TLS handshake first, and older clients that can't.
	TLSHandshakeFirstFallback time.Duration `json:"-"`
	AllowNonTLS               bool          `json:"-"`
	WriteDeadline             time.Duration `json:"-"`
	MaxClosedClients          int           `json:"-"`
	LameDuckDuration          time.Duration `json:"-"`
	LameDuckGracePeriod       time.Duration `json:"-"`

	// MaxTracedMsgLen is the maximum printable length for traced messages.
	MaxTracedMsgLen int `json:"-"`

	// Operating a trusted NATS server
	TrustedKeys              []string              `json:"-"`
	TrustedOperators         []*jwt.OperatorClaims `json:"-"`
	AccountResolver          AccountResolver       `json:"-"`
	AccountResolverTLSConfig *tls.Config           `json:"-"`

	// AlwaysEnableNonce will always present a nonce to new connections
	// typically used by custom Authentication implementations who embeds
	// the server and so not presented as a configuration option
	AlwaysEnableNonce bool

	CustomClientAuthentication Authentication `json:"-"`
	CustomRouterAuthentication Authentication `json:"-"`

	// CheckConfig configuration file syntax test was successful and exit.
	CheckConfig bool `json:"-"`

	// DisableJetStreamBanner will not print the ascii art on startup for JetStream enabled servers
	DisableJetStreamBanner bool `json:"-"`

	// ConnectErrorReports specifies the number of failed attempts
	// at which point server should report the failure of an initial
	// connection to a route, gateway or leaf node.
	// See DEFAULT_CONNECT_ERROR_REPORTS for default value.
	ConnectErrorReports int

	// ReconnectErrorReports is similar to ConnectErrorReports except
	// that this applies to reconnect events.
	ReconnectErrorReports int

	// Tags describing the server. They will be included in varz
	// and used as a filter criteria for some system requests.
	Tags jwt.TagList `json:"-"`

	// OCSPConfig enables OCSP Stapling in the server.
	OCSPConfig    *OCSPConfig
	tlsConfigOpts *TLSConfigOpts

	// private fields, used to know if bool options are explicitly
	// defined in config and/or command line params.
	inConfig  map[string]bool
	inCmdLine map[string]bool

	// private fields for operator mode
	operatorJWT            []string
	resolverPreloads       map[string]string
	resolverPinnedAccounts map[string]struct{}

	// private fields, used for testing
	gatewaysSolicitDelay time.Duration
	routeProto           int

	// JetStream
	maxMemSet   bool
	maxStoreSet bool
	syncSet     bool

	// OCSP Cache config enables next-gen cache for OCSP features
	OCSPCacheConfig *OCSPResponseCacheConfig

	// Used to mark that we had a top level authorization block.
	authBlockDefined bool
}

// WebsocketOpts are options for websocket
type WebsocketOpts struct {
	// The server will accept websocket client connections on this hostname/IP.
	Host string
	// The server will accept websocket client connections on this port.
	Port int
	// The host:port to advertise to websocket clients in the cluster.
	Advertise string

	// If no user name is provided when a client connects, will default to the
	// matching user from the global list of users in `Options.Users`.
	NoAuthUser string

	// Name of the cookie, which if present in WebSocket upgrade headers,
	// will be treated as JWT during CONNECT phase as long as
	// "jwt" specified in the CONNECT options is missing or empty.
	JWTCookie string

	// Authentication section. If anything is configured in this section,
	// it will override the authorization configuration of regular clients.
	Username string
	Password string
	Token    string

	// Timeout for the authentication process.
	AuthTimeout float64

	// By default the server will enforce the use of TLS. If no TLS configuration
	// is provided, you need to explicitly set NoTLS to true to allow the server
	// to start without TLS configuration. Note that if a TLS configuration is
	// present, this boolean is ignored and the server will run the Websocket
	// server with that TLS configuration.
	// Running without TLS is less secure since Websocket clients that use bearer
	// tokens will send them in clear. So this should not be used in production.
	NoTLS bool

	// TLS configuration is required.
	TLSConfig *tls.Config
	// If true, map certificate values for authentication purposes.
	TLSMap bool

	// When present, accepted client certificates (verify/verify_and_map) must be in this list
	TLSPinnedCerts PinnedCertSet

	// If true, the Origin header must match the request's host.
	SameOrigin bool

	// Only origins in this list will be accepted. If empty and
	// SameOrigin is false, any origin is accepted.
	AllowedOrigins []string

	// If set to true, the server will negotiate with clients
	// if compression can be used. If this is false, no compression
	// will be used (both in server and clients) since it has to
	// be negotiated between both endpoints
	Compression bool

	// Total time allowed for the server to read the client request
	// and write the response back to the client. This include the
	// time needed for the TLS Handshake.
	HandshakeTimeout time.Duration

	// Snapshot of configured TLS options.
	tlsConfigOpts *TLSConfigOpts
}

// MQTTOpts are options for MQTT
type MQTTOpts struct {
	// The server will accept MQTT client connections on this hostname/IP.
	Host string
	// The server will accept MQTT client connections on this port.
	Port int

	// If no user name is provided when a client connects, will default to the
	// matching user from the global list of users in `Options.Users`.
	NoAuthUser string

	// Authentication section. If anything is configured in this section,
	// it will override the authorization configuration of regular clients.
	Username string
	Password string
	Token    string

	// JetStream domain mqtt is supposed to pick up
	JsDomain string

	// Number of replicas for MQTT streams.
	// Negative or 0 value means that the server(s) will pick a replica
	// number based on the known size of the cluster (but capped at 3).
	// Note that if an account was already connected, the stream's replica
	// count is not modified. Use the NATS CLI to update the count if desired.
	StreamReplicas int

	// Number of replicas for MQTT consumers.
	// Negative or 0 value means that there is no override and the consumer
	// will have the same replica factor that the stream it belongs to.
	// If a value is specified, it will require to be lower than the stream
	// replicas count (lower than StreamReplicas if specified, but also lower
	// than the automatic value determined by cluster size).
	// Note that existing consumers are not modified.
	//
	// UPDATE: This is no longer used while messages stream has interest policy retention
	// which requires consumer replica count to match the parent stream.
	ConsumerReplicas int

	// Indicate if the consumers should be created with memory storage.
	// Note that existing consumers are not modified.
	ConsumerMemoryStorage bool

	// If specified will have the system auto-cleanup the consumers after being
	// inactive for the specified amount of time.
	ConsumerInactiveThreshold time.Duration

	// Timeout for the authentication process.
	AuthTimeout float64

	// TLS configuration is required.
	TLSConfig *tls.Config
	// If true, map certificate values for authentication purposes.
	TLSMap bool
	// Timeout for the TLS handshake
	TLSTimeout float64
	// Set of allowable certificates
	TLSPinnedCerts PinnedCertSet

	// AckWait is the amount of time after which a QoS 1 or 2 message sent to a
	// client is redelivered as a DUPLICATE if the server has not received the
	// PUBACK on the original Packet Identifier. The same value applies to
	// PubRel redelivery. The value has to be positive. Zero will cause the
	// server to use the default value (30 seconds). Note that changes to this
	// option is applied only to new MQTT subscriptions (or sessions for
	// PubRels).
	AckWait time.Duration

	// MaxAckPending is the amount of QoS 1 and 2 messages (combined) the server
	// can send to a subscription without receiving any PUBACK for those
	// messages. The valid range is [0..65535].
	//
	// The total of subscriptions' MaxAckPending on a given session cannot
	// exceed 65535. Attempting to create a subscription that would bring the
	// total above the limit would result in the server returning 0x80 in the
	// SUBACK for this subscription.
	//
	// Due to how the NATS Server handles the MQTT "#" wildcard, each
	// subscription ending with "#" will use 2 times the MaxAckPending value.
	// Note that changes to this option is applied only to new subscriptions.
	MaxAckPending uint16

	// Snapshot of configured TLS options.
	tlsConfigOpts *TLSConfigOpts

	// rejectQoS2Pub tells the MQTT client to not accept QoS2 PUBLISH, instead
	// error and terminate the connection.
	rejectQoS2Pub bool

	// downgradeQOS2Sub tells the MQTT client to downgrade QoS2 SUBSCRIBE
	// requests to QoS1.
	downgradeQoS2Sub bool
}

type netResolver interface {
	LookupHost(ctx context.Context, host string) ([]string, error)
}

// Clone performs a deep copy of the Options struct, returning a new clone
// with all values copied.
func (o *Options) Clone() *Options {
	if o == nil {
		return nil
	}
	clone := &Options{}
	*clone = *o
	if o.Users != nil {
		clone.Users = make([]*User, len(o.Users))
		for i, user := range o.Users {
			clone.Users[i] = user.clone()
		}
	}
	if o.Nkeys != nil {
		clone.Nkeys = make([]*NkeyUser, len(o.Nkeys))
		for i, nkey := range o.Nkeys {
			clone.Nkeys[i] = nkey.clone()
		}
	}

	if o.Routes != nil {
		clone.Routes = deepCopyURLs(o.Routes)
	}
	if o.TLSConfig != nil {
		clone.TLSConfig = o.TLSConfig.Clone()
	}
	if o.Cluster.TLSConfig != nil {
		clone.Cluster.TLSConfig = o.Cluster.TLSConfig.Clone()
	}
	if o.Gateway.TLSConfig != nil {
		clone.Gateway.TLSConfig = o.Gateway.TLSConfig.Clone()
	}
	if len(o.Gateway.Gateways) > 0 {
		clone.Gateway.Gateways = make([]*RemoteGatewayOpts, len(o.Gateway.Gateways))
		for i, g := range o.Gateway.Gateways {
			clone.Gateway.Gateways[i] = g.clone()
		}
	}
	// FIXME(dlc) - clone leaf node stuff.
	return clone
}

func deepCopyURLs(urls []*url.URL) []*url.URL {
	if urls == nil {
		return nil
	}
	curls := make([]*url.URL, len(urls))
	for i, u := range urls {
		cu := &url.URL{}
		*cu = *u
		curls[i] = cu
	}
	return curls
}

// Configuration file authorization section.
type authorization struct {
	// Singles
	user  string
	pass  string
	token string
	nkey  string
	acc   string
	// Multiple Nkeys/Users
	nkeys              []*NkeyUser
	users              []*User
	timeout            float64
	defaultPermissions *Permissions
	// Auth Callouts
	callout *AuthCallout
}

// TLSConfigOpts holds the parsed tls config information,
// used with flag parsing
type TLSConfigOpts struct {
	CertFile             string
	KeyFile              string
	CaFile               string
	Verify               bool
	Insecure             bool
	Map                  bool
	TLSCheckKnownURLs    bool
	HandshakeFirst       bool          // Indicate that the TLS handshake should occur first, before sending the INFO protocol.
	FallbackDelay        time.Duration // Where supported, indicates how long to wait for the handshake before falling back to sending the INFO protocol first.
	Timeout              float64
	RateLimit            int64
	Ciphers              []uint16
	CurvePreferences     []tls.CurveID
	PinnedCerts          PinnedCertSet
	CertStore            certstore.StoreType
	CertMatchBy          certstore.MatchByType
	CertMatch            string
	CertMatchSkipInvalid bool
	CaCertsMatch         []string
	OCSPPeerConfig       *certidp.OCSPPeerConfig
	Certificates         []*TLSCertPairOpt
	MinVersion           uint16
}

// TLSCertPairOpt are the paths to a certificate and private key.
type TLSCertPairOpt struct {
	CertFile string
	KeyFile  string
}

// OCSPConfig represents the options of OCSP stapling options.
type OCSPConfig struct {
	// Mode defines the policy for OCSP stapling.
	Mode OCSPMode

	// OverrideURLs is the http URL endpoint used to get OCSP staples.
	OverrideURLs []string
}

var tlsUsage = `
TLS configuration is specified in the tls section of a configuration file:

e.g.

    tls {
        cert_file:      "./certs/server-cert.pem"
        key_file:       "./certs/server-key.pem"
        ca_file:        "./certs/ca.pem"
        verify:         true
        verify_and_map: true

        cipher_suites: [
            "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
            "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
        ]
        curve_preferences: [
            "CurveP256",
            "CurveP384",
            "CurveP521"
        ]
    }

Available cipher suites include:
`

// ProcessConfigFile processes a configuration file.
// FIXME(dlc): A bit hacky
func ProcessConfigFile(configFile string) (*Options, error) {
	opts := &Options{}
	if err := opts.ProcessConfigFile(configFile); err != nil {
		// If only warnings then continue and return the options.
		if cerr, ok := err.(*processConfigErr); ok && len(cerr.Errors()) == 0 {
			return opts, nil
		}

		return nil, err
	}
	return opts, nil
}

// token is an item parsed from the configuration.
type token interface {
	Value() any
	Line() int
	IsUsedVariable() bool
	SourceFile() string
	Position() int
}

// unwrapValue can be used to get the token and value from an item
// to be able to report the line number in case of an incorrect
// configuration.
// also stores the token in lastToken for use in convertPanicToError
func unwrapValue(v any, lastToken *token) (token, any) {
	switch tk := v.(type) {
	case token:
		if lastToken != nil {
			*lastToken = tk
		}
		return tk, tk.Value()
	default:
		return nil, v
	}
}

// use in defer to recover from panic and turn it into an error associated with last token
func convertPanicToErrorList(lastToken *token, errors *[]error) {
	// only recover if an error can be stored
	if errors == nil {
		return
	} else if err := recover(); err == nil {
		return
	} else if lastToken != nil && *lastToken != nil {
		*errors = append(*errors, &configErr{*lastToken, fmt.Sprint(err)})
	} else {
		*errors = append(*errors, fmt.Errorf("encountered panic without a token %v", err))
	}
}

// use in defer to recover from panic and turn it into an error associated with last token
func convertPanicToError(lastToken *token, e *error) {
	// only recover if an error can be stored
	if e == nil || *e != nil {
		return
	} else if err := recover(); err == nil {
		return
	} else if lastToken != nil && *lastToken != nil {
		*e = &configErr{*lastToken, fmt.Sprint(err)}
	} else {
		*e = fmt.Errorf("%v", err)
	}
}

// configureSystemAccount configures a system account
// if present in the configuration.
func configureSystemAccount(o *Options, m map[string]any) (retErr error) {
	var lt token
	defer convertPanicToError(&lt, &retErr)
	configure := func(v any) error {
		tk, v := unwrapValue(v, &lt)
		sa, ok := v.(string)
		if !ok {
			return &configErr{tk, "system account name must be a string"}
		}
		o.SystemAccount = sa
		return nil
	}

	if v, ok := m["system_account"]; ok {
		return configure(v)
	} else if v, ok := m["system"]; ok {
		return configure(v)
	}

	return nil
}

// ProcessConfigFile updates the Options structure with options
// present in the given configuration file.
// This version is convenient if one wants to set some default
// options and then override them with what is in the config file.
// For instance, this version allows you to do something such as:
//
// opts := &Options{Debug: true}
// opts.ProcessConfigFile(myConfigFile)
//
// If the config file contains "debug: false", after this call,
// opts.Debug would really be false. It would be impossible to
// achieve that with the non receiver ProcessConfigFile() version,
// since one would not know after the call if "debug" was not present
// or was present but set to false.
func (o *Options) ProcessConfigFile(configFile string) error {
	o.ConfigFile = configFile
	if configFile == _EMPTY_ {
		return nil
	}
	m, err := conf.ParseFileWithChecks(configFile)
	if err != nil {
		return err
	}
	// Collect all errors and warnings and report them all together.
	errors := make([]error, 0)
	warnings := make([]error, 0)
	if len(m) == 0 {
		warnings = append(warnings, fmt.Errorf("%s: config has no values or is empty", configFile))
	}

	// First check whether a system account has been defined,
	// as that is a condition for other features to be enabled.
	if err := configureSystemAccount(o, m); err != nil {
		errors = append(errors, err)
	}

	for k, v := range m {
		o.processConfigFileLine(k, v, &errors, &warnings)
	}

	if len(errors) > 0 || len(warnings) > 0 {
		return &processConfigErr{
			errors:   errors,
			warnings: warnings,
		}
	}

	return nil
}

func (o *Options) processConfigFileLine(k string, v any, errors *[]error, warnings *[]error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	switch strings.ToLower(k) {
	case "listen":
		hp, err := parseListen(v)
		if err != nil {
			*errors = append(*errors, &configErr{tk, err.Error()})
			return
		}
		o.Host = hp.host
		o.Port = hp.port
	case "client_advertise":
		o.ClientAdvertise = v.(string)
	case "port":
		o.Port = int(v.(int64))
	case "server_name":
		o.ServerName = v.(string)
	case "host", "net":
		o.Host = v.(string)
	case "debug":
		o.Debug = v.(bool)
		trackExplicitVal(&o.inConfig, "Debug", o.Debug)
	case "trace":
		o.Trace = v.(bool)
		trackExplicitVal(&o.inConfig, "Trace", o.Trace)
	case "trace_verbose":
		o.TraceVerbose = v.(bool)
		o.Trace = v.(bool)
		trackExplicitVal(&o.inConfig, "TraceVerbose", o.TraceVerbose)
		trackExplicitVal(&o.inConfig, "Trace", o.Trace)
	case "logtime":
		o.Logtime = v.(bool)
		trackExplicitVal(&o.inConfig, "Logtime", o.Logtime)
	case "logtime_utc":
		o.LogtimeUTC = v.(bool)
		trackExplicitVal(&o.inConfig, "LogtimeUTC", o.LogtimeUTC)
	case "mappings", "maps":
		gacc := NewAccount(globalAccountName)
		o.Accounts = append(o.Accounts, gacc)
		err := parseAccountMappings(tk, gacc, errors)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
	case "disable_sublist_cache", "no_sublist_cache":
		o.NoSublistCache = v.(bool)
	case "accounts":
		err := parseAccounts(tk, o, errors, warnings)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
	case "authorization":
		auth, err := parseAuthorization(tk, errors)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
		o.authBlockDefined = true
		o.Username = auth.user
		o.Password = auth.pass
		o.Authorization = auth.token
		o.AuthTimeout = auth.timeout
		o.AuthCallout = auth.callout

		if (auth.user != _EMPTY_ || auth.pass != _EMPTY_) && auth.token != _EMPTY_ {
			err := &configErr{tk, "Cannot have a user/pass and token"}
			*errors = append(*errors, err)
			return
		}
		// In case parseAccounts() was done first, we need to check for duplicates.
		unames := setupUsersAndNKeysDuplicateCheckMap(o)
		// Check for multiple users defined.
		// Note: auth.users will be != nil as long as `users: []` is present
		// in the authorization block, even if empty, and will also account for
		// nkey users. We also check for users/nkeys that may have been already
		// added in parseAccounts() (which means they will be in unames)
		if auth.users != nil || len(unames) > 0 {
			if auth.user != _EMPTY_ {
				err := &configErr{tk, "Can not have a single user/pass and a users array"}
				*errors = append(*errors, err)
				return
			}
			if auth.token != _EMPTY_ {
				err := &configErr{tk, "Can not have a token and a users array"}
				*errors = append(*errors, err)
				return
			}
			// Now check that if we have users, there is no duplicate, including
			// users that may have been configured in parseAccounts().
			if len(auth.users) > 0 {
				for _, u := range auth.users {
					if _, ok := unames[u.Username]; ok {
						err := &configErr{tk, fmt.Sprintf("Duplicate user %q detected", u.Username)}
						*errors = append(*errors, err)
						return
					}
					unames[u.Username] = struct{}{}
				}
				// Users may have been added from Accounts parsing, so do an append here
				o.Users = append(o.Users, auth.users...)
			}
		}
		// Check for nkeys
		if len(auth.nkeys) > 0 {
			for _, u := range auth.nkeys {
				if _, ok := unames[u.Nkey]; ok {
					err := &configErr{tk, fmt.Sprintf("Duplicate nkey %q detected", u.Nkey)}
					*errors = append(*errors, err)
					return
				}
				unames[u.Nkey] = struct{}{}
			}
			// NKeys may have been added from Accounts parsing, so do an append here
			o.Nkeys = append(o.Nkeys, auth.nkeys...)
		}
	case "http":
		hp, err := parseListen(v)
		if err != nil {
			err := &configErr{tk, err.Error()}
			*errors = append(*errors, err)
			return
		}
		o.HTTPHost = hp.host
		o.HTTPPort = hp.port
	case "https":
		hp, err := parseListen(v)
		if err != nil {
			err := &configErr{tk, err.Error()}
			*errors = append(*errors, err)
			return
		}
		o.HTTPHost = hp.host
		o.HTTPSPort = hp.port
	case "http_port", "monitor_port":
		o.HTTPPort = int(v.(int64))
	case "https_port":
		o.HTTPSPort = int(v.(int64))
	case "http_base_path":
		o.HTTPBasePath = v.(string)
	case "cluster":
		err := parseCluster(tk, o, errors, warnings)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
	case "gateway":
		if err := parseGateway(tk, o, errors, warnings); err != nil {
			*errors = append(*errors, err)
			return
		}
	case "leaf", "leafnodes":
		err := parseLeafNodes(tk, o, errors, warnings)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
	case "store_dir", "storedir":
		// Check if JetStream configuration is also setting the storage directory.
		if o.StoreDir != _EMPTY_ {
			*errors = append(*errors, &configErr{tk, "Duplicate 'store_dir' configuration"})
			return
		}
		o.StoreDir = v.(string)
	case "jetstream":
		err := parseJetStream(tk, o, errors, warnings)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
	case "logfile", "log_file":
		o.LogFile = v.(string)
	case "logfile_size_limit", "log_size_limit":
		o.LogSizeLimit = v.(int64)
	case "logfile_max_num", "log_max_num":
		o.LogMaxFiles = v.(int64)
	case "syslog":
		o.Syslog = v.(bool)
		trackExplicitVal(&o.inConfig, "Syslog", o.Syslog)
	case "remote_syslog":
		o.RemoteSyslog = v.(string)
	case "pidfile", "pid_file":
		o.PidFile = v.(string)
	case "ports_file_dir":
		o.PortsFileDir = v.(string)
	case "prof_port":
		o.ProfPort = int(v.(int64))
	case "prof_block_rate":
		o.ProfBlockRate = int(v.(int64))
	case "max_control_line":
		if v.(int64) > 1<<31-1 {
			err := &configErr{tk, fmt.Sprintf("%s value is too big", k)}
			*errors = append(*errors, err)
			return
		}
		o.MaxControlLine = int32(v.(int64))
	case "max_payload":
		if v.(int64) > 1<<31-1 {
			err := &configErr{tk, fmt.Sprintf("%s value is too big", k)}
			*errors = append(*errors, err)
			return
		}
		o.MaxPayload = int32(v.(int64))
	case "max_pending":
		o.MaxPending = v.(int64)
	case "max_connections", "max_conn":
		o.MaxConn = int(v.(int64))
	case "max_traced_msg_len":
		o.MaxTracedMsgLen = int(v.(int64))
	case "max_subscriptions", "max_subs":
		o.MaxSubs = int(v.(int64))
	case "max_sub_tokens", "max_subscription_tokens":
		if n := v.(int64); n > math.MaxUint8 {
			err := &configErr{tk, fmt.Sprintf("%s value is too big", k)}
			*errors = append(*errors, err)
			return
		} else if n <= 0 {
			err := &configErr{tk, fmt.Sprintf("%s value can not be negative", k)}
			*errors = append(*errors, err)
			return
		} else {
			o.MaxSubTokens = uint8(n)
		}
	case "ping_interval":
		o.PingInterval = parseDuration("ping_interval", tk, v, errors, warnings)
	case "ping_max":
		o.MaxPingsOut = int(v.(int64))
	case "tls":
		tc, err := parseTLS(tk, true)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
		if o.TLSConfig, err = GenTLSConfig(tc); err != nil {
			err := &configErr{tk, err.Error()}
			*errors = append(*errors, err)
			return
		}
		o.TLSTimeout = tc.Timeout
		o.TLSMap = tc.Map
		o.TLSPinnedCerts = tc.PinnedCerts
		o.TLSRateLimit = tc.RateLimit
		o.TLSHandshakeFirst = tc.HandshakeFirst
		o.TLSHandshakeFirstFallback = tc.FallbackDelay

		// Need to keep track of path of the original TLS config
		// and certs path for OCSP Stapling monitoring.
		o.tlsConfigOpts = tc
	case "ocsp":
		switch vv := v.(type) {
		case bool:
			if vv {
				// Default is Auto which honors Must Staple status request
				// but does not shutdown the server in case it is revoked,
				// letting the client choose whether to trust or not the server.
				o.OCSPConfig = &OCSPConfig{Mode: OCSPModeAuto}
			} else {
				o.OCSPConfig = &OCSPConfig{Mode: OCSPModeNever}
			}
		case map[string]any:
			ocsp := &OCSPConfig{Mode: OCSPModeAuto}

			for kk, kv := range vv {
				_, v = unwrapValue(kv, &tk)
				switch kk {
				case "mode":
					mode := v.(string)
					switch {
					case strings.EqualFold(mode, "always"):
						ocsp.Mode = OCSPModeAlways
					case strings.EqualFold(mode, "must"):
						ocsp.Mode = OCSPModeMust
					case strings.EqualFold(mode, "never"):
						ocsp.Mode = OCSPModeNever
					case strings.EqualFold(mode, "auto"):
						ocsp.Mode = OCSPModeAuto
					default:
						*errors = append(*errors, &configErr{tk, fmt.Sprintf("error parsing ocsp config: unsupported ocsp mode %T", mode)})
					}
				case "urls":
					urls := v.([]string)
					ocsp.OverrideURLs = urls
				case "url":
					url := v.(string)
					ocsp.OverrideURLs = []string{url}
				default:
					*errors = append(*errors, &configErr{tk, fmt.Sprintf("error parsing ocsp config: unsupported field %T", kk)})
					return
				}
			}
			o.OCSPConfig = ocsp
		default:
			*errors = append(*errors, &configErr{tk, fmt.Sprintf("error parsing ocsp config: unsupported type %T", v)})
			return
		}
	case "allow_non_tls":
		o.AllowNonTLS = v.(bool)
	case "write_deadline":
		o.WriteDeadline = parseDuration("write_deadline", tk, v, errors, warnings)
	case "lame_duck_duration":
		dur, err := time.ParseDuration(v.(string))
		if err != nil {
			err := &configErr{tk, fmt.Sprintf("error parsing lame_duck_duration: %v", err)}
			*errors = append(*errors, err)
			return
		}
		if dur < 30*time.Second {
			err := &configErr{tk, fmt.Sprintf("invalid lame_duck_duration of %v, minimum is 30 seconds", dur)}
			*errors = append(*errors, err)
			return
		}
		o.LameDuckDuration = dur
	case "lame_duck_grace_period":
		dur, err := time.ParseDuration(v.(string))
		if err != nil {
			err := &configErr{tk, fmt.Sprintf("error parsing lame_duck_grace_period: %v", err)}
			*errors = append(*errors, err)
			return
		}
		if dur < 0 {
			err := &configErr{tk, "invalid lame_duck_grace_period, needs to be positive"}
			*errors = append(*errors, err)
			return
		}
		o.LameDuckGracePeriod = dur
	case "operator", "operators", "roots", "root", "root_operators", "root_operator":
		opFiles := []string{}
		switch v := v.(type) {
		case string:
			opFiles = append(opFiles, v)
		case []string:
			opFiles = append(opFiles, v...)
		case []any:
			for _, t := range v {
				if token, ok := t.(token); ok {
					if v, ok := token.Value().(string); ok {
						opFiles = append(opFiles, v)
					} else {
						err := &configErr{tk, fmt.Sprintf("error parsing operators: unsupported type %T where string is expected", token)}
						*errors = append(*errors, err)
						break
					}
				} else {
					err := &configErr{tk, fmt.Sprintf("error parsing operators: unsupported type %T", t)}
					*errors = append(*errors, err)
					break
				}
			}
		default:
			err := &configErr{tk, fmt.Sprintf("error parsing operators: unsupported type %T", v)}
			*errors = append(*errors, err)
		}
		// Assume for now these are file names, but they can also be the JWT itself inline.
		o.TrustedOperators = make([]*jwt.OperatorClaims, 0, len(opFiles))
		for _, fname := range opFiles {
			theJWT, opc, err := readOperatorJWT(fname)
			if err != nil {
				err := &configErr{tk, fmt.Sprintf("error parsing operator JWT: %v", err)}
				*errors = append(*errors, err)
				continue
			}
			o.operatorJWT = append(o.operatorJWT, theJWT)
			o.TrustedOperators = append(o.TrustedOperators, opc)
		}
		if len(o.TrustedOperators) == 1 {
			// In case "resolver" is defined as well, it takes precedence
			if o.AccountResolver == nil {
				if accUrl, err := parseURL(o.TrustedOperators[0].AccountServerURL, "account resolver"); err == nil {
					// nsc automatically appends "/accounts" during nsc push
					o.AccountResolver, _ = NewURLAccResolver(accUrl.String() + "/accounts")
				}
			}
			// In case "system_account" is defined as well, it takes precedence
			if o.SystemAccount == _EMPTY_ {
				o.SystemAccount = o.TrustedOperators[0].SystemAccount
			}
		}
	case "resolver", "account_resolver", "accounts_resolver":
		switch v := v.(type) {
		case string:
			// "resolver" takes precedence over value obtained from "operator".
			// Clear so that parsing errors are not silently ignored.
			o.AccountResolver = nil
			memResolverRe := regexp.MustCompile(`(?i)(MEM|MEMORY)\s*`)
			resolverRe := regexp.MustCompile(`(?i)(?:URL){1}(?:\({1}\s*"?([^\s"]*)"?\s*\){1})?\s*`)
			if memResolverRe.MatchString(v) {
				o.AccountResolver = &MemAccResolver{}
			} else if items := resolverRe.FindStringSubmatch(v); len(items) == 2 {
				url := items[1]
				_, err := parseURL(url, "account resolver")
				if err != nil {
					*errors = append(*errors, &configErr{tk, err.Error()})
					return
				}
				if ur, err := NewURLAccResolver(url); err != nil {
					err := &configErr{tk, err.Error()}
					*errors = append(*errors, err)
					return
				} else {
					o.AccountResolver = ur
				}
			}
		case map[string]any:
			del := false
			hdel := false
			hdel_set := false
			dir := _EMPTY_
			dirType := _EMPTY_
			limit := int64(0)
			ttl := time.Duration(0)
			sync := time.Duration(0)
			opts := []DirResOption{}
			var err error
			if v, ok := v["dir"]; ok {
				_, v := unwrapValue(v, &lt)
				dir = v.(string)
			}
			if v, ok := v["type"]; ok {
				_, v := unwrapValue(v, &lt)
				dirType = v.(string)
			}
			if v, ok := v["allow_delete"]; ok {
				_, v := unwrapValue(v, &lt)
				del = v.(bool)
			}
			if v, ok := v["hard_delete"]; ok {
				_, v := unwrapValue(v, &lt)
				hdel_set = true
				hdel = v.(bool)
			}
			if v, ok := v["limit"]; ok {
				_, v := unwrapValue(v, &lt)
				limit = v.(int64)
			}
			if v, ok := v["ttl"]; ok {
				_, v := unwrapValue(v, &lt)
				ttl, err = time.ParseDuration(v.(string))
			}
			if v, ok := v["interval"]; err == nil && ok {
				_, v := unwrapValue(v, &lt)
				sync, err = time.ParseDuration(v.(string))
			}
			if v, ok := v["timeout"]; err == nil && ok {
				_, v := unwrapValue(v, &lt)
				var to time.Duration
				if to, err = time.ParseDuration(v.(string)); err == nil {
					opts = append(opts, FetchTimeout(to))
				}
			}
			if err != nil {
				*errors = append(*errors, &configErr{tk, err.Error()})
				return
			}

			checkDir := func() {
				if dir == _EMPTY_ {
					*errors = append(*errors, &configErr{tk, "dir has no value and needs to point to a directory"})
					return
				}
				if info, _ := os.Stat(dir); info != nil && (!info.IsDir() || info.Mode().Perm()&(1<<(uint(7))) == 0) {
					*errors = append(*errors, &configErr{tk, "dir needs to point to an accessible directory"})
					return
				}
			}

			var res AccountResolver
			switch strings.ToUpper(dirType) {
			case "CACHE":
				checkDir()
				if sync != 0 {
					*errors = append(*errors, &configErr{tk, "CACHE does not accept sync"})
				}
				if del {
					*errors = append(*errors, &configErr{tk, "CACHE does not accept allow_delete"})
				}
				if hdel_set {
					*errors = append(*errors, &configErr{tk, "CACHE does not accept hard_delete"})
				}
				res, err = NewCacheDirAccResolver(dir, limit, ttl, opts...)
			case "FULL":
				checkDir()
				if ttl != 0 {
					*errors = append(*errors, &configErr{tk, "FULL does not accept ttl"})
				}
				if hdel_set && !del {
					*errors = append(*errors, &configErr{tk, "hard_delete has no effect without delete"})
				}
				delete := NoDelete
				if del {
					if hdel {
						delete = HardDelete
					} else {
						delete = RenameDeleted
					}
				}
				res, err = NewDirAccResolver(dir, limit, sync, delete, opts...)
			case "MEM", "MEMORY":
				res = &MemAccResolver{}
			}
			if err != nil {
				*errors = append(*errors, &configErr{tk, err.Error()})
				return
			}
			o.AccountResolver = res
		default:
			err := &configErr{tk, fmt.Sprintf("error parsing operator resolver, wrong type %T", v)}
			*errors = append(*errors, err)
			return
		}
		if o.AccountResolver == nil {
			err := &configErr{tk, "error parsing account resolver, should be MEM or " +
				" URL(\"url\") or a map containing dir and type state=[FULL|CACHE])"}
			*errors = append(*errors, err)
		}
	case "resolver_tls":
		tc, err := parseTLS(tk, true)
		if err != nil {
			*errors = append(*errors, err)
			return
		}
		tlsConfig, err := GenTLSConfig(tc)
		if err != nil {
			err := &configErr{tk, err.Error()}
			*errors = append(*errors, err)
			return
		}
		o.AccountResolverTLSConfig = tlsConfig
		// GenTLSConfig loads the CA file into ClientCAs, but since this will
		// be used as a client connection, we need to set RootCAs.
		o.AccountResolverTLSConfig.RootCAs = tlsConfig.ClientCAs
	case "resolver_preload":
		mp, ok := v.(map[string]any)
		if !ok {
			err := &configErr{tk, "preload should be a map of account_public_key:account_jwt"}
			*errors = append(*errors, err)
			return
		}
		o.resolverPreloads = make(map[string]string)
		for key, val := range mp {
			tk, val = unwrapValue(val, &lt)
			if jwtstr, ok := val.(string); !ok {
				*errors = append(*errors, &configErr{tk, "preload map value should be a string JWT"})
				continue
			} else {
				// Make sure this is a valid account JWT, that is a config error.
				// We will warn of expirations, etc later.
				if _, err := jwt.DecodeAccountClaims(jwtstr); err != nil {
					err := &configErr{tk, "invalid account JWT"}
					*errors = append(*errors, err)
					continue
				}
				o.resolverPreloads[key] = jwtstr
			}
		}
	case "resolver_pinned_accounts":
		switch v := v.(type) {
		case string:
			o.resolverPinnedAccounts = map[string]struct{}{v: {}}
		case []string:
			o.resolverPinnedAccounts = make(map[string]struct{})
			for _, mv := range v {
				o.resolverPinnedAccounts[mv] = struct{}{}
			}
		case []any:
			o.resolverPinnedAccounts = make(map[string]struct{})
			for _, mv := range v {
				tk, mv = unwrapValue(mv, &lt)
				if key, ok := mv.(string); ok {
					o.resolverPinnedAccounts[key] = struct{}{}
				} else {
					err := &configErr{tk,
						fmt.Sprintf("error parsing resolver_pinned_accounts: unsupported type in array %T", mv)}
					*errors = append(*errors, err)
					continue
				}
			}
		default:
			err := &configErr{tk, fmt.Sprintf("error parsing resolver_pinned_accounts: unsupported type %T", v)}
			*errors = append(*errors, err)
			return
		}
	case "no_auth_user":
		o.NoAuthUser = v.(string)
	case "system_account", "system":
		// Already processed at the beginning so we just skip them
		// to not treat them as unknown values.
		return
	case "no_system_account", "no_system", "no_sys_acc":
		o.NoSystemAccount = v.(bool)
	case "no_header_support":
		o.NoHeaderSupport = v.(bool)
	case "trusted", "trusted_keys":
		switch v := v.(type) {
		case string:
			o.TrustedKeys = []string{v}
		case []string:
			o.TrustedKeys = v
		case []any:
			keys := make([]string, 0, len(v))
			for _, mv := range v {
				tk, mv = unwrapValue(mv, &lt)
				if key, ok := mv.(string); ok {
					keys = append(keys, key)
				} else {
					err := &configErr{tk, fmt.Sprintf("error parsing trusted: unsupported type in array %T", mv)}
					*errors = append(*errors, err)
					continue
				}
			}
			o.TrustedKeys = keys
		default:
			err := &configErr{tk, fmt.Sprintf("error parsing trusted: unsupported type %T", v)}
			*errors = append(*errors, err)
		}
		// Do a quick sanity check on keys
		for _, key := range o.TrustedKeys {
			if !nkeys.IsValidPublicOperatorKey(key) {
				err := &configErr{tk, fmt.Sprintf("trust key %q required to be a valid public operator nkey", key)}
				*errors = append(*errors, err)
			}
		}
	case "connect_error_reports":
		o.ConnectErrorReports = int(v.(int64))
	case "reconnect_error_reports":
		o.ReconnectErrorReports = int(v.(int64))
	case "websocket", "ws":
		if err := parseWebsocket(tk, o, errors); err != nil {
			*errors = append(*errors, err)
			return
		}
	case "mqtt":
		if err := parseMQTT(tk, o, errors, warnings); err != nil {
			*errors = append(*errors, err)
			return
		}
	case "server_tags":
		var err error
		switch v := v.(type) {
		case string:
			o.Tags.Add(v)
		case []string:
			o.Tags.Add(v...)
		case []any:
			for _, t := range v {
				if token, ok := t.(token); ok {
					if ts, ok := token.Value().(string); ok {
						o.Tags.Add(ts)
						continue
					} else {
						err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T where string is expected", token)}
					}
				} else {
					err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T", t)}
				}
				break
			}
		default:
			err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T", v)}
		}
		if err != nil {
			*errors = append(*errors, err)
			return
		}
	case "default_js_domain":
		vv, ok := v.(map[string]any)
		if !ok {
			*errors = append(*errors, &configErr{tk, fmt.Sprintf("error default_js_domain config: unsupported type %T", v)})
			return
		}
		m := make(map[string]string)
		for kk, kv := range vv {
			_, v = unwrapValue(kv, &tk)
			m[kk] = v.(string)
		}
		o.JsAccDefaultDomain = m
	case "ocsp_cache":
		var err error
		switch vv := v.(type) {
		case bool:
			pc := NewOCSPResponseCacheConfig()
			if vv {
				// Set enabled
				pc.Type = LOCAL
				o.OCSPCacheConfig = pc
			} else {
				// Set disabled (none cache)
				pc.Type = NONE
				o.OCSPCacheConfig = pc
			}
		case map[string]any:
			pc, err := parseOCSPResponseCache(v)
			if err != nil {
				*errors = append(*errors, err)
				return
			}
			o.OCSPCacheConfig = pc
		default:
			err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T", v)}
		}
		if err != nil {
			*errors = append(*errors, err)
			return
		}
	case "no_fast_producer_stall":
		o.NoFastProducerStall = v.(bool)
	case "max_closed_clients":
		o.MaxClosedClients = int(v.(int64))
	default:
		if au := atomic.LoadInt32(&allowUnknownTopLevelField); au == 0 && !tk.IsUsedVariable() {
			err := &unknownConfigFieldErr{
				field: k,
				configErr: configErr{
					token: tk,
				},
			}
			*errors = append(*errors, err)
		}
	}
}

func setupUsersAndNKeysDuplicateCheckMap(o *Options) map[string]struct{} {
	unames := make(map[string]struct{}, len(o.Users)+len(o.Nkeys))
	for _, u := range o.Users {
		unames[u.Username] = struct{}{}
	}
	for _, u := range o.Nkeys {
		unames[u.Nkey] = struct{}{}
	}
	return unames
}

func parseDuration(field string, tk token, v any, errors *[]error, warnings *[]error) time.Duration {
	if wd, ok := v.(string); ok {
		if dur, err := time.ParseDuration(wd); err != nil {
			err := &configErr{tk, fmt.Sprintf("error parsing %s: %v", field, err)}
			*errors = append(*errors, err)
			return 0
		} else {
			return dur
		}
	} else {
		// Backward compatible with old type, assume this is the
		// number of seconds.
		err := &configWarningErr{
			field: field,
			configErr: configErr{
				token:  tk,
				reason: field + " should be converted to a duration",
			},
		}
		*warnings = append(*warnings, err)
		return time.Duration(v.(int64)) * time.Second
	}
}

func trackExplicitVal(pm *map[string]bool, name string, val bool) {
	m := *pm
	if m == nil {
		m = make(map[string]bool)
		*pm = m
	}
	m[name] = val
}

// hostPort is simple struct to hold parsed listen/addr strings.
type hostPort struct {
	host string
	port int
}

// parseListen will parse listen option which is replacing host/net and port
func parseListen(v any) (*hostPort, error) {
	hp := &hostPort{}
	switch vv := v.(type) {
	// Only a port
	case int64:
		hp.port = int(vv)
	case string:
		host, port, err := net.SplitHostPort(vv)
		if err != nil {
			return nil, fmt.Errorf("could not parse address string %q", vv)
		}
		hp.port, err = strconv.Atoi(port)
		if err != nil {
			return nil, fmt.Errorf("could not parse port %q", port)
		}
		hp.host = host
	default:
		return nil, fmt.Errorf("expected port or host:port, got %T", vv)
	}
	return hp, nil
}

// parseCluster will parse the cluster config.
func parseCluster(v any, opts *Options, errors *[]error, warnings *[]error) error {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	cm, ok := v.(map[string]any)
	if !ok {
		return &configErr{tk, fmt.Sprintf("Expected map to define cluster, got %T", v)}
	}

	for mk, mv := range cm {
		// Again, unwrap token value if line check is required.
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "name":
			opts.Cluster.Name = mv.(string)
		case "listen":
			hp, err := parseListen(mv)
			if err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			opts.Cluster.Host = hp.host
			opts.Cluster.Port = hp.port
		case "port":
			opts.Cluster.Port = int(mv.(int64))
		case "host", "net":
			opts.Cluster.Host = mv.(string)
		case "authorization":
			auth, err := parseAuthorization(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if auth.users != nil {
				err := &configErr{tk, "Cluster authorization does not allow multiple users"}
				*errors = append(*errors, err)
				continue
			}
			if auth.token != _EMPTY_ {
				err := &configErr{tk, "Cluster authorization does not support tokens"}
				*errors = append(*errors, err)
				continue
			}
			if auth.callout != nil {
				err := &configErr{tk, "Cluster authorization does not support callouts"}
				*errors = append(*errors, err)
				continue
			}

			opts.Cluster.Username = auth.user
			opts.Cluster.Password = auth.pass
			opts.Cluster.AuthTimeout = auth.timeout

			if auth.defaultPermissions != nil {
				err := &configWarningErr{
					field: mk,
					configErr: configErr{
						token:  tk,
						reason: `setting "permissions" within cluster authorization block is deprecated`,
					},
				}
				*warnings = append(*warnings, err)

				// Do not set permissions if they were specified in top-level cluster block.
				if opts.Cluster.Permissions == nil {
					setClusterPermissions(&opts.Cluster, auth.defaultPermissions)
				}
			}
		case "routes":
			ra := mv.([]any)
			routes, errs := parseURLs(ra, "route", warnings)
			if errs != nil {
				*errors = append(*errors, errs...)
				continue
			}
			opts.Routes = routes
		case "tls":
			config, tlsopts, err := getTLSConfig(tk)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			opts.Cluster.TLSConfig = config
			opts.Cluster.TLSTimeout = tlsopts.Timeout
			opts.Cluster.TLSMap = tlsopts.Map
			opts.Cluster.TLSPinnedCerts = tlsopts.PinnedCerts
			opts.Cluster.TLSCheckKnownURLs = tlsopts.TLSCheckKnownURLs
			opts.Cluster.tlsConfigOpts = tlsopts
		case "cluster_advertise", "advertise":
			opts.Cluster.Advertise = mv.(string)
		case "no_advertise":
			opts.Cluster.NoAdvertise = mv.(bool)
			trackExplicitVal(&opts.inConfig, "Cluster.NoAdvertise", opts.Cluster.NoAdvertise)
		case "connect_retries":
			opts.Cluster.ConnectRetries = int(mv.(int64))
		case "permissions":
			perms, err := parseUserPermissions(mv, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			// Dynamic response permissions do not make sense here.
			if perms.Response != nil {
				err := &configErr{tk, "Cluster permissions do not support dynamic responses"}
				*errors = append(*errors, err)
				continue
			}
			// This will possibly override permissions that were define in auth block
			setClusterPermissions(&opts.Cluster, perms)
		case "pool_size":
			opts.Cluster.PoolSize = int(mv.(int64))
		case "accounts":
			opts.Cluster.PinnedAccounts, _ = parseStringArray("accounts", tk, &lt, mv, errors)
		case "compression":
			if err := parseCompression(&opts.Cluster.Compression, CompressionS2Fast, tk, mk, mv); err != nil {
				*errors = append(*errors, err)
				continue
			}
		case "ping_interval":
			opts.Cluster.PingInterval = parseDuration("ping_interval", tk, mv, errors, warnings)
			if opts.Cluster.PingInterval > routeMaxPingInterval {
				*warnings = append(*warnings, &configErr{tk, fmt.Sprintf("Cluster 'ping_interval' will reset to %v which is the max for routes", routeMaxPingInterval)})
			}
		case "ping_max":
			opts.Cluster.MaxPingsOut = int(mv.(int64))
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
				continue
			}
		}
	}
	return nil
}

// The parameter `chosenModeForOn` indicates which compression mode to use
// when the user selects "on" (or enabled, true, etc..). This is because
// we may have different defaults depending on where the compression is used.
func parseCompression(c *CompressionOpts, chosenModeForOn string, tk token, mk string, mv any) (retErr error) {
	var lt token
	defer convertPanicToError(&lt, &retErr)

	switch mv := mv.(type) {
	case string:
		// Do not validate here, it will be done in NewServer.
		c.Mode = mv
	case bool:
		if mv {
			c.Mode = chosenModeForOn
		} else {
			c.Mode = CompressionOff
		}
	case map[string]any:
		for mk, mv := range mv {
			tk, mv = unwrapValue(mv, &lt)
			switch strings.ToLower(mk) {
			case "mode":
				c.Mode = mv.(string)
			case "rtt_thresholds", "thresholds", "rtts", "rtt":
				for _, iv := range mv.([]any) {
					_, mv := unwrapValue(iv, &lt)
					dur, err := time.ParseDuration(mv.(string))
					if err != nil {
						return &configErr{tk, err.Error()}
					}
					c.RTTThresholds = append(c.RTTThresholds, dur)
				}
			default:
				if !tk.IsUsedVariable() {
					return &configErr{tk, fmt.Sprintf("unknown field %q", mk)}
				}
			}
		}
	default:
		return &configErr{tk, fmt.Sprintf("field %q should be a boolean or a structure, got %T", mk, mv)}
	}
	return nil
}

func parseURLs(a []any, typ string, warnings *[]error) (urls []*url.URL, errors []error) {
	urls = make([]*url.URL, 0, len(a))
	var lt token
	defer convertPanicToErrorList(&lt, &errors)

	dd := make(map[string]bool)

	for _, u := range a {
		tk, u := unwrapValue(u, &lt)
		sURL := u.(string)
		if dd[sURL] {
			err := &configWarningErr{
				field: sURL,
				configErr: configErr{
					token:  tk,
					reason: fmt.Sprintf("Duplicate %s entry detected", typ),
				},
			}
			*warnings = append(*warnings, err)
			continue
		}
		dd[sURL] = true
		url, err := parseURL(sURL, typ)
		if err != nil {
			err := &configErr{tk, err.Error()}
			errors = append(errors, err)
			continue
		}
		urls = append(urls, url)
	}
	return urls, errors
}

func parseURL(u string, typ string) (*url.URL, error) {
	urlStr := strings.TrimSpace(u)
	url, err := url.Parse(urlStr)
	if err != nil {
		// Security note: if it's not well-formed but still reached us, then we're going to log as-is which might include password information here.
		// If the URL parses, we don't log the credentials ever, but if it doesn't even parse we don't have a sane way to redact.
		return nil, fmt.Errorf("error parsing %s url [%q]", typ, urlStr)
	}
	return url, nil
}

func parseGateway(v any, o *Options, errors *[]error, warnings *[]error) error {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	gm, ok := v.(map[string]any)
	if !ok {
		return &configErr{tk, fmt.Sprintf("Expected gateway to be a map, got %T", v)}
	}
	for mk, mv := range gm {
		// Again, unwrap token value if line check is required.
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "name":
			o.Gateway.Name = mv.(string)
		case "listen":
			hp, err := parseListen(mv)
			if err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			o.Gateway.Host = hp.host
			o.Gateway.Port = hp.port
		case "port":
			o.Gateway.Port = int(mv.(int64))
		case "host", "net":
			o.Gateway.Host = mv.(string)
		case "authorization":
			auth, err := parseAuthorization(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if auth.users != nil {
				*errors = append(*errors, &configErr{tk, "Gateway authorization does not allow multiple users"})
				continue
			}
			if auth.token != _EMPTY_ {
				err := &configErr{tk, "Gateway authorization does not support tokens"}
				*errors = append(*errors, err)
				continue
			}
			if auth.callout != nil {
				err := &configErr{tk, "Gateway authorization does not support callouts"}
				*errors = append(*errors, err)
				continue
			}

			o.Gateway.Username = auth.user
			o.Gateway.Password = auth.pass
			o.Gateway.AuthTimeout = auth.timeout
		case "tls":
			config, tlsopts, err := getTLSConfig(tk)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			o.Gateway.TLSConfig = config
			o.Gateway.TLSTimeout = tlsopts.Timeout
			o.Gateway.TLSMap = tlsopts.Map
			o.Gateway.TLSCheckKnownURLs = tlsopts.TLSCheckKnownURLs
			o.Gateway.TLSPinnedCerts = tlsopts.PinnedCerts
			o.Gateway.tlsConfigOpts = tlsopts
		case "advertise":
			o.Gateway.Advertise = mv.(string)
		case "connect_retries":
			o.Gateway.ConnectRetries = int(mv.(int64))
		case "gateways":
			gateways, err := parseGateways(mv, errors, warnings)
			if err != nil {
				return err
			}
			o.Gateway.Gateways = gateways
		case "reject_unknown", "reject_unknown_cluster":
			o.Gateway.RejectUnknown = mv.(bool)
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
				continue
			}
		}
	}
	return nil
}

var dynamicJSAccountLimits = JetStreamAccountLimits{-1, -1, -1, -1, -1, -1, -1, false}
var defaultJSAccountTiers = map[string]JetStreamAccountLimits{_EMPTY_: dynamicJSAccountLimits}

// Parses jetstream account limits for an account. Simple setup with boolen is allowed, and we will
// use dynamic account limits.
func parseJetStreamForAccount(v any, acc *Account, errors *[]error) error {
	var lt token

	tk, v := unwrapValue(v, &lt)

	// Value here can be bool, or string "enabled" or a map.
	switch vv := v.(type) {
	case bool:
		if vv {
			acc.jsLimits = defaultJSAccountTiers
		}
	case string:
		switch strings.ToLower(vv) {
		case "enabled", "enable":
			acc.jsLimits = defaultJSAccountTiers
		case "disabled", "disable":
			acc.jsLimits = nil
		default:
			return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)}
		}
	case map[string]any:
		jsLimits := JetStreamAccountLimits{-1, -1, -1, -1, -1, -1, -1, false}
		for mk, mv := range vv {
			tk, mv = unwrapValue(mv, &lt)
			switch strings.ToLower(mk) {
			case "max_memory", "max_mem", "mem", "memory":
				vv, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				jsLimits.MaxMemory = vv
			case "max_store", "max_file", "max_disk", "store", "disk":
				vv, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				jsLimits.MaxStore = vv
			case "max_streams", "streams":
				vv, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				jsLimits.MaxStreams = int(vv)
			case "max_consumers", "consumers":
				vv, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				jsLimits.MaxConsumers = int(vv)
			case "max_bytes_required", "max_stream_bytes", "max_bytes":
				vv, ok := mv.(bool)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable bool for %q, got %v", mk, mv)}
				}
				jsLimits.MaxBytesRequired = vv
			case "mem_max_stream_bytes", "memory_max_stream_bytes":
				vv, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				jsLimits.MemoryMaxStreamBytes = vv
			case "disk_max_stream_bytes", "store_max_stream_bytes":
				vv, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				jsLimits.StoreMaxStreamBytes = vv
			case "max_ack_pending":
				vv, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				jsLimits.MaxAckPending = int(vv)
			default:
				if !tk.IsUsedVariable() {
					err := &unknownConfigFieldErr{
						field: mk,
						configErr: configErr{
							token: tk,
						},
					}
					*errors = append(*errors, err)
					continue
				}
			}
		}
		acc.jsLimits = map[string]JetStreamAccountLimits{_EMPTY_: jsLimits}
	default:
		return &configErr{tk, fmt.Sprintf("Expected map, bool or string to define JetStream, got %T", v)}
	}
	return nil
}

// takes in a storage size as either an int or a string and returns an int64 value based on the input.
func getStorageSize(v any) (int64, error) {
	_, ok := v.(int64)
	if ok {
		return v.(int64), nil
	}

	s, ok := v.(string)
	if !ok {
		return 0, fmt.Errorf("must be int64 or string")
	}

	if s == _EMPTY_ {
		return 0, nil
	}

	suffix := s[len(s)-1:]
	prefix := s[:len(s)-1]
	num, err := strconv.ParseInt(prefix, 10, 64)
	if err != nil {
		return 0, err
	}

	suffixMap := map[string]int64{"K": 10, "M": 20, "G": 30, "T": 40}

	mult, ok := suffixMap[suffix]
	if !ok {
		return 0, fmt.Errorf("sizes defined as strings must end in K, M, G, T")
	}
	num *= 1 << mult

	return num, nil
}

// Parse enablement of jetstream for a server.
func parseJetStreamLimits(v any, opts *Options, errors *[]error) error {
	var lt token
	tk, v := unwrapValue(v, &lt)

	lim := JSLimitOpts{}

	vv, ok := v.(map[string]any)
	if !ok {
		return &configErr{tk, fmt.Sprintf("Expected a map to define JetStreamLimits, got %T", v)}
	}
	for mk, mv := range vv {
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "max_ack_pending":
			lim.MaxAckPending = int(mv.(int64))
		case "max_ha_assets":
			lim.MaxHAAssets = int(mv.(int64))
		case "max_request_batch":
			lim.MaxRequestBatch = int(mv.(int64))
		case "duplicate_window":
			var err error
			lim.Duplicates, err = time.ParseDuration(mv.(string))
			if err != nil {
				*errors = append(*errors, err)
			}
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
				continue
			}
		}
	}
	opts.JetStreamLimits = lim
	return nil
}

// Parse enablement of jetstream for a server.
func parseJetStream(v any, opts *Options, errors *[]error, warnings *[]error) error {
	var lt token

	tk, v := unwrapValue(v, &lt)

	// Value here can be bool, or string "enabled" or a map.
	switch vv := v.(type) {
	case bool:
		opts.JetStream = v.(bool)
	case string:
		switch strings.ToLower(vv) {
		case "enabled", "enable":
			opts.JetStream = true
		case "disabled", "disable":
			opts.JetStream = false
		default:
			return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)}
		}
	case map[string]any:
		doEnable := true
		for mk, mv := range vv {
			tk, mv = unwrapValue(mv, &lt)
			switch strings.ToLower(mk) {
			case "store", "store_dir", "storedir":
				// StoreDir can be set at the top level as well so have to prevent ambiguous declarations.
				if opts.StoreDir != _EMPTY_ {
					return &configErr{tk, "Duplicate 'store_dir' configuration"}
				}
				opts.StoreDir = mv.(string)
			case "sync", "sync_interval":
				if v, ok := mv.(string); ok && strings.ToLower(v) == "always" {
					opts.SyncInterval = defaultSyncInterval
					opts.SyncAlways = true
				} else {
					opts.SyncInterval = parseDuration(mk, tk, mv, errors, warnings)
				}
				opts.syncSet = true
			case "max_memory_store", "max_mem_store", "max_mem":
				s, err := getStorageSize(mv)
				if err != nil {
					return &configErr{tk, fmt.Sprintf("max_mem_store %s", err)}
				}
				opts.JetStreamMaxMemory = s
				opts.maxMemSet = true
			case "max_file_store", "max_file":
				s, err := getStorageSize(mv)
				if err != nil {
					return &configErr{tk, fmt.Sprintf("max_file_store %s", err)}
				}
				opts.JetStreamMaxStore = s
				opts.maxStoreSet = true
			case "domain":
				opts.JetStreamDomain = mv.(string)
			case "enable", "enabled":
				doEnable = mv.(bool)
			case "key", "ek", "encryption_key":
				opts.JetStreamKey = mv.(string)
			case "prev_key", "prev_ek", "prev_encryption_key":
				opts.JetStreamOldKey = mv.(string)
			case "cipher":
				switch strings.ToLower(mv.(string)) {
				case "chacha", "chachapoly":
					opts.JetStreamCipher = ChaCha
				case "aes":
					opts.JetStreamCipher = AES
				default:
					return &configErr{tk, fmt.Sprintf("Unknown cipher type: %q", mv)}
				}
			case "extension_hint":
				opts.JetStreamExtHint = mv.(string)
			case "limits":
				if err := parseJetStreamLimits(tk, opts, errors); err != nil {
					return err
				}
			case "unique_tag":
				opts.JetStreamUniqueTag = strings.ToLower(strings.TrimSpace(mv.(string)))
			case "max_outstanding_catchup":
				s, err := getStorageSize(mv)
				if err != nil {
					return &configErr{tk, fmt.Sprintf("%s %s", strings.ToLower(mk), err)}
				}
				opts.JetStreamMaxCatchup = s
			case "request_queue_limit":
				lim, ok := mv.(int64)
				if !ok {
					return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)}
				}
				opts.JetStreamRequestQueueLimit = lim
			default:
				if !tk.IsUsedVariable() {
					err := &unknownConfigFieldErr{
						field: mk,
						configErr: configErr{
							token: tk,
						},
					}
					*errors = append(*errors, err)
					continue
				}
			}
		}
		opts.JetStream = doEnable
	default:
		return &configErr{tk, fmt.Sprintf("Expected map, bool or string to define JetStream, got %T", v)}
	}

	return nil
}

// parseLeafNodes will parse the leaf node config.
func parseLeafNodes(v any, opts *Options, errors *[]error, warnings *[]error) error {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	cm, ok := v.(map[string]any)
	if !ok {
		return &configErr{tk, fmt.Sprintf("Expected map to define a leafnode, got %T", v)}
	}

	for mk, mv := range cm {
		// Again, unwrap token value if line check is required.
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "listen":
			hp, err := parseListen(mv)
			if err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			opts.LeafNode.Host = hp.host
			opts.LeafNode.Port = hp.port
		case "port":
			opts.LeafNode.Port = int(mv.(int64))
		case "host", "net":
			opts.LeafNode.Host = mv.(string)
		case "authorization":
			auth, err := parseLeafAuthorization(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			opts.LeafNode.Username = auth.user
			opts.LeafNode.Password = auth.pass
			opts.LeafNode.AuthTimeout = auth.timeout
			opts.LeafNode.Account = auth.acc
			opts.LeafNode.Users = auth.users
			opts.LeafNode.Nkey = auth.nkey
			// Validate user info config for leafnode authorization
			if err := validateLeafNodeAuthOptions(opts); err != nil {
				*errors = append(*errors, &configErr{tk, err.Error()})
				continue
			}
		case "remotes":
			// Parse the remote options here.
			remotes, err := parseRemoteLeafNodes(tk, errors, warnings)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			opts.LeafNode.Remotes = remotes
		case "reconnect", "reconnect_delay", "reconnect_interval":
			opts.LeafNode.ReconnectInterval = parseDuration("reconnect", tk, mv, errors, warnings)
		case "tls":
			tc, err := parseTLS(tk, true)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if opts.LeafNode.TLSConfig, err = GenTLSConfig(tc); err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			opts.LeafNode.TLSTimeout = tc.Timeout
			opts.LeafNode.TLSMap = tc.Map
			opts.LeafNode.TLSPinnedCerts = tc.PinnedCerts
			opts.LeafNode.TLSHandshakeFirst = tc.HandshakeFirst
			opts.LeafNode.tlsConfigOpts = tc
		case "leafnode_advertise", "advertise":
			opts.LeafNode.Advertise = mv.(string)
		case "no_advertise":
			opts.LeafNode.NoAdvertise = mv.(bool)
			trackExplicitVal(&opts.inConfig, "LeafNode.NoAdvertise", opts.LeafNode.NoAdvertise)
		case "min_version", "minimum_version":
			version := mv.(string)
			if err := checkLeafMinVersionConfig(version); err != nil {
				err = &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			opts.LeafNode.MinVersion = version
		case "compression":
			if err := parseCompression(&opts.LeafNode.Compression, CompressionS2Auto, tk, mk, mv); err != nil {
				*errors = append(*errors, err)
				continue
			}
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
				continue
			}
		}
	}
	return nil
}

// This is the authorization parser adapter for the leafnode's
// authorization config.
func parseLeafAuthorization(v any, errors *[]error) (*authorization, error) {
	var (
		am   map[string]any
		tk   token
		lt   token
		auth = &authorization{}
	)
	defer convertPanicToErrorList(&lt, errors)

	_, v = unwrapValue(v, &lt)
	am = v.(map[string]any)
	for mk, mv := range am {
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "user", "username":
			auth.user = mv.(string)
		case "pass", "password":
			auth.pass = mv.(string)
		case "nkey":
			nk := mv.(string)
			if !nkeys.IsValidPublicUserKey(nk) {
				*errors = append(*errors, &configErr{tk, "Not a valid public nkey for leafnode authorization"})
			}
			auth.nkey = nk
		case "timeout":
			at := float64(1)
			switch mv := mv.(type) {
			case int64:
				at = float64(mv)
			case float64:
				at = mv
			}
			auth.timeout = at
		case "users":
			users, err := parseLeafUsers(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			auth.users = users
		case "account":
			auth.acc = mv.(string)
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
			}
			continue
		}
	}
	return auth, nil
}

// This is a trimmed down version of parseUsers that is adapted
// for the users possibly defined in the authorization{} section
// of leafnodes {}.
func parseLeafUsers(mv any, errors *[]error) ([]*User, error) {
	var (
		tk    token
		lt    token
		users = []*User{}
	)
	defer convertPanicToErrorList(&lt, errors)

	tk, mv = unwrapValue(mv, &lt)
	// Make sure we have an array
	uv, ok := mv.([]any)
	if !ok {
		return nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)}
	}
	for _, u := range uv {
		tk, u = unwrapValue(u, &lt)
		// Check its a map/struct
		um, ok := u.(map[string]any)
		if !ok {
			err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)}
			*errors = append(*errors, err)
			continue
		}
		user := &User{}
		for k, v := range um {
			tk, v = unwrapValue(v, &lt)
			switch strings.ToLower(k) {
			case "user", "username":
				user.Username = v.(string)
			case "pass", "password":
				user.Password = v.(string)
			case "account":
				// We really want to save just the account name here, but
				// the User object is *Account. So we create an account object
				// but it won't be registered anywhere. The server will just
				// use opts.LeafNode.Users[].Account.Name. Alternatively
				// we need to create internal objects to store u/p and account
				// name and have a server structure to hold that.
				user.Account = NewAccount(v.(string))
			default:
				if !tk.IsUsedVariable() {
					err := &unknownConfigFieldErr{
						field: k,
						configErr: configErr{
							token: tk,
						},
					}
					*errors = append(*errors, err)
					continue
				}
			}
		}
		users = append(users, user)
	}
	return users, nil
}

func parseRemoteLeafNodes(v any, errors *[]error, warnings *[]error) ([]*RemoteLeafOpts, error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)
	tk, v := unwrapValue(v, &lt)
	ra, ok := v.([]any)
	if !ok {
		return nil, &configErr{tk, fmt.Sprintf("Expected remotes field to be an array, got %T", v)}
	}
	remotes := make([]*RemoteLeafOpts, 0, len(ra))
	for _, r := range ra {
		tk, r = unwrapValue(r, &lt)
		// Check its a map/struct
		rm, ok := r.(map[string]any)
		if !ok {
			*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected remote leafnode entry to be a map/struct, got %v", r)})
			continue
		}
		remote := &RemoteLeafOpts{}
		for k, v := range rm {
			tk, v = unwrapValue(v, &lt)
			switch strings.ToLower(k) {
			case "no_randomize", "dont_randomize":
				remote.NoRandomize = v.(bool)
			case "url", "urls":
				switch v := v.(type) {
				case []any, []string:
					urls, errs := parseURLs(v.([]any), "leafnode", warnings)
					if errs != nil {
						*errors = append(*errors, errs...)
						continue
					}
					remote.URLs = urls
				case string:
					url, err := parseURL(v, "leafnode")
					if err != nil {
						*errors = append(*errors, &configErr{tk, err.Error()})
						continue
					}
					remote.URLs = append(remote.URLs, url)
				default:
					*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected remote leafnode url to be an array or string, got %v", v)})
					continue
				}
			case "account", "local":
				remote.LocalAccount = v.(string)
			case "creds", "credentials":
				p, err := expandPath(v.(string))
				if err != nil {
					*errors = append(*errors, &configErr{tk, err.Error()})
					continue
				}
				// Can't have both creds and nkey
				if remote.Nkey != _EMPTY_ {
					*errors = append(*errors, &configErr{tk, "Remote leafnode can not have both creds and nkey defined"})
					continue
				}
				remote.Credentials = p
			case "nkey", "seed":
				nk := v.(string)
				if pb, _, err := nkeys.DecodeSeed([]byte(nk)); err != nil || pb != nkeys.PrefixByteUser {
					err := &configErr{tk, fmt.Sprintf("Remote leafnode nkey is not a valid seed: %q", v)}
					*errors = append(*errors, err)
					continue
				}
				if remote.Credentials != _EMPTY_ {
					*errors = append(*errors, &configErr{tk, "Remote leafnode can not have both creds and nkey defined"})
					continue
				}
				remote.Nkey = nk
			case "tls":
				tc, err := parseTLS(tk, true)
				if err != nil {
					*errors = append(*errors, err)
					continue
				}
				if remote.TLSConfig, err = GenTLSConfig(tc); err != nil {
					*errors = append(*errors, &configErr{tk, err.Error()})
					continue
				}
				// If ca_file is defined, GenTLSConfig() sets TLSConfig.ClientCAs.
				// Set RootCAs since this tls.Config is used when soliciting
				// a connection (therefore behaves as a client).
				remote.TLSConfig.RootCAs = remote.TLSConfig.ClientCAs
				if tc.Timeout > 0 {
					remote.TLSTimeout = tc.Timeout
				} else {
					remote.TLSTimeout = float64(DEFAULT_LEAF_TLS_TIMEOUT) / float64(time.Second)
				}
				remote.TLSHandshakeFirst = tc.HandshakeFirst
				remote.tlsConfigOpts = tc
			case "hub":
				remote.Hub = v.(bool)
			case "deny_imports", "deny_import":
				subjects, err := parsePermSubjects(tk, errors)
				if err != nil {
					*errors = append(*errors, err)
					continue
				}
				remote.DenyImports = subjects
			case "deny_exports", "deny_export":
				subjects, err := parsePermSubjects(tk, errors)
				if err != nil {
					*errors = append(*errors, err)
					continue
				}
				remote.DenyExports = subjects
			case "ws_compress", "ws_compression", "websocket_compress", "websocket_compression":
				remote.Websocket.Compression = v.(bool)
			case "ws_no_masking", "websocket_no_masking":
				remote.Websocket.NoMasking = v.(bool)
			case "jetstream_cluster_migrate", "js_cluster_migrate":
				remote.JetStreamClusterMigrate = true
			case "compression":
				if err := parseCompression(&remote.Compression, CompressionS2Auto, tk, k, v); err != nil {
					*errors = append(*errors, err)
					continue
				}
			case "first_info_timeout":
				remote.FirstInfoTimeout = parseDuration(k, tk, v, errors, warnings)
			default:
				if !tk.IsUsedVariable() {
					err := &unknownConfigFieldErr{
						field: k,
						configErr: configErr{
							token: tk,
						},
					}
					*errors = append(*errors, err)
					continue
				}
			}
		}
		remotes = append(remotes, remote)
	}
	return remotes, nil
}

// Parse TLS and returns a TLSConfig and TLSTimeout.
// Used by cluster and gateway parsing.
func getTLSConfig(tk token) (*tls.Config, *TLSConfigOpts, error) {
	tc, err := parseTLS(tk, false)
	if err != nil {
		return nil, nil, err
	}
	config, err := GenTLSConfig(tc)
	if err != nil {
		err := &configErr{tk, err.Error()}
		return nil, nil, err
	}
	// For clusters/gateways, we will force strict verification. We also act
	// as both client and server, so will mirror the rootCA to the
	// clientCA pool.
	config.ClientAuth = tls.RequireAndVerifyClientCert
	config.RootCAs = config.ClientCAs
	return config, tc, nil
}

func parseGateways(v any, errors *[]error, warnings *[]error) ([]*RemoteGatewayOpts, error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	// Make sure we have an array
	ga, ok := v.([]any)
	if !ok {
		return nil, &configErr{tk, fmt.Sprintf("Expected gateways field to be an array, got %T", v)}
	}
	gateways := []*RemoteGatewayOpts{}
	for _, g := range ga {
		tk, g = unwrapValue(g, &lt)
		// Check its a map/struct
		gm, ok := g.(map[string]any)
		if !ok {
			*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected gateway entry to be a map/struct, got %v", g)})
			continue
		}
		gateway := &RemoteGatewayOpts{}
		for k, v := range gm {
			tk, v = unwrapValue(v, &lt)
			switch strings.ToLower(k) {
			case "name":
				gateway.Name = v.(string)
			case "tls":
				tls, tlsopts, err := getTLSConfig(tk)
				if err != nil {
					*errors = append(*errors, err)
					continue
				}
				gateway.TLSConfig = tls
				gateway.TLSTimeout = tlsopts.Timeout
				gateway.tlsConfigOpts = tlsopts
			case "url":
				url, err := parseURL(v.(string), "gateway")
				if err != nil {
					*errors = append(*errors, &configErr{tk, err.Error()})
					continue
				}
				gateway.URLs = append(gateway.URLs, url)
			case "urls":
				urls, errs := parseURLs(v.([]any), "gateway", warnings)
				if errs != nil {
					*errors = append(*errors, errs...)
					continue
				}
				gateway.URLs = urls
			default:
				if !tk.IsUsedVariable() {
					err := &unknownConfigFieldErr{
						field: k,
						configErr: configErr{
							token: tk,
						},
					}
					*errors = append(*errors, err)
					continue
				}
			}
		}
		gateways = append(gateways, gateway)
	}
	return gateways, nil
}

// Sets cluster's permissions based on given pub/sub permissions,
// doing the appropriate translation.
func setClusterPermissions(opts *ClusterOpts, perms *Permissions) {
	// Import is whether or not we will send a SUB for interest to the other side.
	// Export is whether or not we will accept a SUB from the remote for a given subject.
	// Both only effect interest registration.
	// The parsing sets Import into Publish and Export into Subscribe, convert
	// accordingly.
	opts.Permissions = &RoutePermissions{
		Import: perms.Publish,
		Export: perms.Subscribe,
	}
}

// Temp structures to hold account import and export defintions since they need
// to be processed after being parsed.
type export struct {
	acc  *Account
	sub  string
	accs []string
	rt   ServiceRespType
	lat  *serviceLatency
	rthr time.Duration
	tPos uint
}

type importStream struct {
	acc *Account
	an  string
	sub string
	to  string
	pre string
}

type importService struct {
	acc   *Account
	an    string
	sub   string
	to    string
	share bool
}

// Checks if an account name is reserved.
func isReservedAccount(name string) bool {
	return name == globalAccountName
}

func parseAccountMapDest(v any, tk token, errors *[]error) (*MapDest, *configErr) {
	// These should be maps.
	mv, ok := v.(map[string]any)
	if !ok {
		err := &configErr{tk, "Expected an entry for the mapping destination"}
		*errors = append(*errors, err)
		return nil, err
	}

	mdest := &MapDest{}
	var lt token
	var sw bool

	for k, v := range mv {
		tk, dmv := unwrapValue(v, &lt)
		switch strings.ToLower(k) {
		case "dest", "destination":
			mdest.Subject = dmv.(string)
		case "weight":
			switch vv := dmv.(type) {
			case string:
				ws := vv
				ws = strings.TrimSuffix(ws, "%")
				weight, err := strconv.Atoi(ws)
				if err != nil {
					err := &configErr{tk, fmt.Sprintf("Invalid weight %q for mapping destination", ws)}
					*errors = append(*errors, err)
					return nil, err
				}
				if weight > 100 || weight < 0 {
					err := &configErr{tk, fmt.Sprintf("Invalid weight %d for mapping destination", weight)}
					*errors = append(*errors, err)
					return nil, err
				}
				mdest.Weight = uint8(weight)
				sw = true
			case int64:
				weight := vv
				if weight > 100 || weight < 0 {
					err := &configErr{tk, fmt.Sprintf("Invalid weight %d for mapping destination", weight)}
					*errors = append(*errors, err)
					return nil, err
				}
				mdest.Weight = uint8(weight)
				sw = true
			default:
				err := &configErr{tk, fmt.Sprintf("Unknown entry type for weight of %v\n", vv)}
				*errors = append(*errors, err)
				return nil, err
			}
		case "cluster":
			mdest.Cluster = dmv.(string)
		default:
			err := &configErr{tk, fmt.Sprintf("Unknown field %q for mapping destination", k)}
			*errors = append(*errors, err)
			return nil, err
		}
	}

	if !sw {
		err := &configErr{tk, fmt.Sprintf("Missing weight for mapping destination %q", mdest.Subject)}
		*errors = append(*errors, err)
		return nil, err
	}

	return mdest, nil
}

// parseAccountMappings is called to parse account mappings.
func parseAccountMappings(v any, acc *Account, errors *[]error) error {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	am := v.(map[string]any)
	for subj, mv := range am {
		if !IsValidSubject(subj) {
			err := &configErr{tk, fmt.Sprintf("Subject %q is not a valid subject", subj)}
			*errors = append(*errors, err)
			continue
		}
		tk, v := unwrapValue(mv, &lt)

		switch vv := v.(type) {
		case string:
			if err := acc.AddMapping(subj, v.(string)); err != nil {
				err := &configErr{tk, fmt.Sprintf("Error adding mapping for %q to %q : %v", subj, v.(string), err)}
				*errors = append(*errors, err)
				continue
			}
		case []any:
			var mappings []*MapDest
			for _, mv := range v.([]any) {
				tk, amv := unwrapValue(mv, &lt)
				mdest, err := parseAccountMapDest(amv, tk, errors)
				if err != nil {
					continue
				}
				mappings = append(mappings, mdest)
			}

			// Now add them in..
			if err := acc.AddWeightedMappings(subj, mappings...); err != nil {
				err := &configErr{tk, fmt.Sprintf("Error adding mapping for %q : %v", subj, err)}
				*errors = append(*errors, err)
				continue
			}
		case any:
			tk, amv := unwrapValue(mv, &lt)
			mdest, err := parseAccountMapDest(amv, tk, errors)
			if err != nil {
				continue
			}
			// Now add it in..
			if err := acc.AddWeightedMappings(subj, mdest); err != nil {
				err := &configErr{tk, fmt.Sprintf("Error adding mapping for %q : %v", subj, err)}
				*errors = append(*errors, err)
				continue
			}
		default:
			err := &configErr{tk, fmt.Sprintf("Unknown type %T for mapping destination", vv)}
			*errors = append(*errors, err)
			continue
		}
	}

	return nil
}

// parseAccountLimits is called to parse account limits in a server config.
func parseAccountLimits(mv any, acc *Account, errors *[]error) error {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(mv, &lt)
	am, ok := v.(map[string]any)
	if !ok {
		return &configErr{tk, fmt.Sprintf("Expected account limits to be a map/struct, got %+v", v)}
	}

	for k, v := range am {
		tk, mv = unwrapValue(v, &lt)
		switch strings.ToLower(k) {
		case "max_connections", "max_conn":
			acc.mconns = int32(mv.(int64))
		case "max_subscriptions", "max_subs":
			acc.msubs = int32(mv.(int64))
		case "max_payload", "max_pay":
			acc.mpay = int32(mv.(int64))
		case "max_leafnodes", "max_leafs":
			acc.mleafs = int32(mv.(int64))
		default:
			if !tk.IsUsedVariable() {
				err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing account limits", k)}
				*errors = append(*errors, err)
			}
		}
	}

	return nil
}

// parseAccounts will parse the different accounts syntax.
func parseAccounts(v any, opts *Options, errors *[]error, warnings *[]error) error {
	var (
		importStreams  []*importStream
		importServices []*importService
		exportStreams  []*export
		exportServices []*export
		lt             token
	)
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	switch vv := v.(type) {
	// Simple array of account names.
	case []any, []string:
		m := make(map[string]struct{}, len(v.([]any)))
		for _, n := range v.([]any) {
			tk, name := unwrapValue(n, &lt)
			ns := name.(string)
			// Check for reserved names.
			if isReservedAccount(ns) {
				err := &configErr{tk, fmt.Sprintf("%q is a Reserved Account", ns)}
				*errors = append(*errors, err)
				continue
			}
			if _, ok := m[ns]; ok {
				err := &configErr{tk, fmt.Sprintf("Duplicate Account Entry: %s", ns)}
				*errors = append(*errors, err)
				continue
			}
			opts.Accounts = append(opts.Accounts, NewAccount(ns))
			m[ns] = struct{}{}
		}
	// More common map entry
	case map[string]any:
		// Track users across accounts, must be unique across
		// accounts and nkeys vs users.
		// We also want to check for users that may have been added in
		// parseAuthorization{} if that happened first.
		uorn := setupUsersAndNKeysDuplicateCheckMap(opts)

		for aname, mv := range vv {
			tk, amv := unwrapValue(mv, &lt)

			// Skip referenced config vars within the account block.
			if tk.IsUsedVariable() {
				continue
			}

			// These should be maps.
			mv, ok := amv.(map[string]any)
			if !ok {
				err := &configErr{tk, "Expected map entries for accounts"}
				*errors = append(*errors, err)
				continue
			}
			if isReservedAccount(aname) {
				err := &configErr{tk, fmt.Sprintf("%q is a Reserved Account", aname)}
				*errors = append(*errors, err)
				continue
			}
			var (
				users   []*User
				nkeyUsr []*NkeyUser
				usersTk token
			)
			acc := NewAccount(aname)
			opts.Accounts = append(opts.Accounts, acc)

			for k, v := range mv {
				tk, mv := unwrapValue(v, &lt)
				switch strings.ToLower(k) {
				case "nkey":
					nk, ok := mv.(string)
					if !ok || !nkeys.IsValidPublicAccountKey(nk) {
						err := &configErr{tk, fmt.Sprintf("Not a valid public nkey for an account: %q", mv)}
						*errors = append(*errors, err)
						continue
					}
					acc.Nkey = nk
				case "imports":
					streams, services, err := parseAccountImports(tk, acc, errors)
					if err != nil {
						*errors = append(*errors, err)
						continue
					}
					importStreams = append(importStreams, streams...)
					importServices = append(importServices, services...)
				case "exports":
					streams, services, err := parseAccountExports(tk, acc, errors)
					if err != nil {
						*errors = append(*errors, err)
						continue
					}
					exportStreams = append(exportStreams, streams...)
					exportServices = append(exportServices, services...)
				case "jetstream":
					err := parseJetStreamForAccount(mv, acc, errors)
					if err != nil {
						*errors = append(*errors, err)
						continue
					}
				case "users":
					var err error
					usersTk = tk
					nkeyUsr, users, err = parseUsers(mv, errors)
					if err != nil {
						*errors = append(*errors, err)
						continue
					}
				case "default_permissions":
					permissions, err := parseUserPermissions(tk, errors)
					if err != nil {
						*errors = append(*errors, err)
						continue
					}
					acc.defaultPerms = permissions
				case "mappings", "maps":
					err := parseAccountMappings(tk, acc, errors)
					if err != nil {
						*errors = append(*errors, err)
						continue
					}
				case "limits":
					err := parseAccountLimits(tk, acc, errors)
					if err != nil {
						*errors = append(*errors, err)
						continue
					}
				default:
					if !tk.IsUsedVariable() {
						err := &unknownConfigFieldErr{
							field: k,
							configErr: configErr{
								token: tk,
							},
						}
						*errors = append(*errors, err)
					}
				}
			}
			// Report error if there is an authorization{} block
			// with u/p or token and any user defined in accounts{}
			if len(nkeyUsr) > 0 || len(users) > 0 {
				if opts.Username != _EMPTY_ {
					err := &configErr{usersTk, "Can not have a single user/pass and accounts"}
					*errors = append(*errors, err)
					continue
				}
				if opts.Authorization != _EMPTY_ {
					err := &configErr{usersTk, "Can not have a token and accounts"}
					*errors = append(*errors, err)
					continue
				}
			}
			applyDefaultPermissions(users, nkeyUsr, acc.defaultPerms)
			for _, u := range nkeyUsr {
				if _, ok := uorn[u.Nkey]; ok {
					err := &configErr{usersTk, fmt.Sprintf("Duplicate nkey %q detected", u.Nkey)}
					*errors = append(*errors, err)
					continue
				}
				uorn[u.Nkey] = struct{}{}
				u.Account = acc
			}
			opts.Nkeys = append(opts.Nkeys, nkeyUsr...)
			for _, u := range users {
				if _, ok := uorn[u.Username]; ok {
					err := &configErr{usersTk, fmt.Sprintf("Duplicate user %q detected", u.Username)}
					*errors = append(*errors, err)
					continue
				}
				uorn[u.Username] = struct{}{}
				u.Account = acc
			}
			opts.Users = append(opts.Users, users...)
		}
	}
	lt = tk
	// Bail already if there are previous errors.
	if len(*errors) > 0 {
		return nil
	}

	// Parse Imports and Exports here after all accounts defined.
	// Do exports first since they need to be defined for imports to succeed
	// since we do permissions checks.

	// Create a lookup map for accounts lookups.
	am := make(map[string]*Account, len(opts.Accounts))
	for _, a := range opts.Accounts {
		am[a.Name] = a
	}
	// Do stream exports
	for _, stream := range exportStreams {
		// Make array of accounts if applicable.
		var accounts []*Account
		for _, an := range stream.accs {
			ta := am[an]
			if ta == nil {
				msg := fmt.Sprintf("%q account not defined for stream export", an)
				*errors = append(*errors, &configErr{tk, msg})
				continue
			}
			accounts = append(accounts, ta)
		}
		if err := stream.acc.addStreamExportWithAccountPos(stream.sub, accounts, stream.tPos); err != nil {
			msg := fmt.Sprintf("Error adding stream export %q: %v", stream.sub, err)
			*errors = append(*errors, &configErr{tk, msg})
			continue
		}
	}
	for _, service := range exportServices {
		// Make array of accounts if applicable.
		var accounts []*Account
		for _, an := range service.accs {
			ta := am[an]
			if ta == nil {
				msg := fmt.Sprintf("%q account not defined for service export", an)
				*errors = append(*errors, &configErr{tk, msg})
				continue
			}
			accounts = append(accounts, ta)
		}
		if err := service.acc.addServiceExportWithResponseAndAccountPos(service.sub, service.rt, accounts, service.tPos); err != nil {
			msg := fmt.Sprintf("Error adding service export %q: %v", service.sub, err)
			*errors = append(*errors, &configErr{tk, msg})
			continue
		}

		if service.rthr != 0 {
			// Response threshold was set in options.
			if err := service.acc.SetServiceExportResponseThreshold(service.sub, service.rthr); err != nil {
				msg := fmt.Sprintf("Error adding service export response threshold for %q: %v", service.sub, err)
				*errors = append(*errors, &configErr{tk, msg})
				continue
			}
		}

		if service.lat != nil {
			// System accounts are on be default so just make sure we have not opted out..
			if opts.NoSystemAccount {
				msg := fmt.Sprintf("Error adding service latency sampling for %q: %v", service.sub, ErrNoSysAccount.Error())
				*errors = append(*errors, &configErr{tk, msg})
				continue
			}

			if err := service.acc.TrackServiceExportWithSampling(service.sub, service.lat.subject, int(service.lat.sampling)); err != nil {
				msg := fmt.Sprintf("Error adding service latency sampling for %q on subject %q: %v", service.sub, service.lat.subject, err)
				*errors = append(*errors, &configErr{tk, msg})
				continue
			}
		}
	}
	for _, stream := range importStreams {
		ta := am[stream.an]
		if ta == nil {
			msg := fmt.Sprintf("%q account not defined for stream import", stream.an)
			*errors = append(*errors, &configErr{tk, msg})
			continue
		}
		if stream.pre != _EMPTY_ {
			if err := stream.acc.AddStreamImport(ta, stream.sub, stream.pre); err != nil {
				msg := fmt.Sprintf("Error adding stream import %q: %v", stream.sub, err)
				*errors = append(*errors, &configErr{tk, msg})
				continue
			}
		} else {
			if err := stream.acc.AddMappedStreamImport(ta, stream.sub, stream.to); err != nil {
				msg := fmt.Sprintf("Error adding stream import %q: %v", stream.sub, err)
				*errors = append(*errors, &configErr{tk, msg})
				continue
			}
		}
	}
	for _, service := range importServices {
		ta := am[service.an]
		if ta == nil {
			msg := fmt.Sprintf("%q account not defined for service import", service.an)
			*errors = append(*errors, &configErr{tk, msg})
			continue
		}
		if service.to == _EMPTY_ {
			service.to = service.sub
		}
		if err := service.acc.AddServiceImport(ta, service.to, service.sub); err != nil {
			msg := fmt.Sprintf("Error adding service import %q: %v", service.sub, err)
			*errors = append(*errors, &configErr{tk, msg})
			continue
		}
		if err := service.acc.SetServiceImportSharing(ta, service.sub, service.share); err != nil {
			msg := fmt.Sprintf("Error setting service import sharing %q: %v", service.sub, err)
			*errors = append(*errors, &configErr{tk, msg})
			continue
		}
	}

	return nil
}

// Parse the account exports
func parseAccountExports(v any, acc *Account, errors *[]error) ([]*export, []*export, error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	// This should be an array of objects/maps.
	tk, v := unwrapValue(v, &lt)
	ims, ok := v.([]any)
	if !ok {
		return nil, nil, &configErr{tk, fmt.Sprintf("Exports should be an array, got %T", v)}
	}

	var services []*export
	var streams []*export

	for _, v := range ims {
		// Should have stream or service
		stream, service, err := parseExportStreamOrService(v, errors)
		if err != nil {
			*errors = append(*errors, err)
			continue
		}
		if service != nil {
			service.acc = acc
			services = append(services, service)
		}
		if stream != nil {
			stream.acc = acc
			streams = append(streams, stream)
		}
	}
	return streams, services, nil
}

// Parse the account imports
func parseAccountImports(v any, acc *Account, errors *[]error) ([]*importStream, []*importService, error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	// This should be an array of objects/maps.
	tk, v := unwrapValue(v, &lt)
	ims, ok := v.([]any)
	if !ok {
		return nil, nil, &configErr{tk, fmt.Sprintf("Imports should be an array, got %T", v)}
	}

	var services []*importService
	var streams []*importStream
	svcSubjects := map[string]*importService{}

	for _, v := range ims {
		// Should have stream or service
		stream, service, err := parseImportStreamOrService(v, errors)
		if err != nil {
			*errors = append(*errors, err)
			continue
		}
		if service != nil {
			if dup := svcSubjects[service.to]; dup != nil {
				tk, _ := unwrapValue(v, &lt)
				err := &configErr{tk,
					fmt.Sprintf("Duplicate service import subject %q, previously used in import for account %q, subject %q",
						service.to, dup.an, dup.sub)}
				*errors = append(*errors, err)
				continue
			}
			svcSubjects[service.to] = service
			service.acc = acc
			services = append(services, service)
		}
		if stream != nil {
			stream.acc = acc
			streams = append(streams, stream)
		}
	}
	return streams, services, nil
}

// Helper to parse an embedded account description for imported services or streams.
func parseAccount(v map[string]any, errors *[]error) (string, string, error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	var accountName, subject string
	for mk, mv := range v {
		tk, mv := unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "account":
			accountName = mv.(string)
		case "subject":
			subject = mv.(string)
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
			}
		}
	}
	return accountName, subject, nil
}

// Parse an export stream or service.
// e.g.
// {stream: "public.>"} # No accounts means public.
// {stream: "synadia.private.>", accounts: [cncf, natsio]}
// {service: "pub.request"} # No accounts means public.
// {service: "pub.special.request", accounts: [nats.io]}
func parseExportStreamOrService(v any, errors *[]error) (*export, *export, error) {
	var (
		curStream  *export
		curService *export
		accounts   []string
		rt         ServiceRespType
		rtSeen     bool
		rtToken    token
		lat        *serviceLatency
		threshSeen bool
		thresh     time.Duration
		latToken   token
		lt         token
		accTokPos  uint
	)
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	vv, ok := v.(map[string]any)
	if !ok {
		return nil, nil, &configErr{tk, fmt.Sprintf("Export Items should be a map with type entry, got %T", v)}
	}
	for mk, mv := range vv {
		tk, mv := unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "stream":
			if curService != nil {
				err := &configErr{tk, fmt.Sprintf("Detected stream %q but already saw a service", mv)}
				*errors = append(*errors, err)
				continue
			}
			if rtToken != nil {
				err := &configErr{rtToken, "Detected response directive on non-service"}
				*errors = append(*errors, err)
				continue
			}
			if latToken != nil {
				err := &configErr{latToken, "Detected latency directive on non-service"}
				*errors = append(*errors, err)
				continue
			}
			mvs, ok := mv.(string)
			if !ok {
				err := &configErr{tk, fmt.Sprintf("Expected stream name to be string, got %T", mv)}
				*errors = append(*errors, err)
				continue
			}
			curStream = &export{sub: mvs}
			if accounts != nil {
				curStream.accs = accounts
			}
		case "service":
			if curStream != nil {
				err := &configErr{tk, fmt.Sprintf("Detected service %q but already saw a stream", mv)}
				*errors = append(*errors, err)
				continue
			}
			mvs, ok := mv.(string)
			if !ok {
				err := &configErr{tk, fmt.Sprintf("Expected service name to be string, got %T", mv)}
				*errors = append(*errors, err)
				continue
			}
			curService = &export{sub: mvs}
			if accounts != nil {
				curService.accs = accounts
			}
			if rtSeen {
				curService.rt = rt
			}
			if lat != nil {
				curService.lat = lat
			}
			if threshSeen {
				curService.rthr = thresh
			}
		case "response", "response_type":
			if rtSeen {
				err := &configErr{tk, "Duplicate response type definition"}
				*errors = append(*errors, err)
				continue
			}
			rtSeen = true
			rtToken = tk
			mvs, ok := mv.(string)
			if !ok {
				err := &configErr{tk, fmt.Sprintf("Expected response type to be string, got %T", mv)}
				*errors = append(*errors, err)
				continue
			}
			switch strings.ToLower(mvs) {
			case "single", "singleton":
				rt = Singleton
			case "stream":
				rt = Streamed
			case "chunk", "chunked":
				rt = Chunked
			default:
				err := &configErr{tk, fmt.Sprintf("Unknown response type: %q", mvs)}
				*errors = append(*errors, err)
				continue
			}
			if curService != nil {
				curService.rt = rt
			}
			if curStream != nil {
				err := &configErr{tk, "Detected response directive on non-service"}
				*errors = append(*errors, err)
			}
		case "threshold", "response_threshold", "response_max_time", "response_time":
			if threshSeen {
				err := &configErr{tk, "Duplicate response threshold detected"}
				*errors = append(*errors, err)
				continue
			}
			threshSeen = true
			mvs, ok := mv.(string)
			if !ok {
				err := &configErr{tk, fmt.Sprintf("Expected response threshold to be a parseable time duration, got %T", mv)}
				*errors = append(*errors, err)
				continue
			}
			var err error
			thresh, err = time.ParseDuration(mvs)
			if err != nil {
				err := &configErr{tk, fmt.Sprintf("Expected response threshold to be a parseable time duration, got %q", mvs)}
				*errors = append(*errors, err)
				continue
			}
			if curService != nil {
				curService.rthr = thresh
			}
			if curStream != nil {
				err := &configErr{tk, "Detected response directive on non-service"}
				*errors = append(*errors, err)
			}
		case "accounts":
			for _, iv := range mv.([]any) {
				_, mv := unwrapValue(iv, &lt)
				accounts = append(accounts, mv.(string))
			}
			if curStream != nil {
				curStream.accs = accounts
			} else if curService != nil {
				curService.accs = accounts
			}
		case "latency":
			latToken = tk
			var err error
			lat, err = parseServiceLatency(tk, mv)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if curStream != nil {
				err = &configErr{tk, "Detected latency directive on non-service"}
				*errors = append(*errors, err)
				continue
			}
			if curService != nil {
				curService.lat = lat
			}
		case "account_token_position":
			accTokPos = uint(mv.(int64))
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
			}
		}
	}
	if curStream != nil {
		curStream.tPos = accTokPos
	}
	if curService != nil {
		curService.tPos = accTokPos
	}
	return curStream, curService, nil
}

// parseServiceLatency returns a latency config block.
func parseServiceLatency(root token, v any) (l *serviceLatency, retErr error) {
	var lt token
	defer convertPanicToError(&lt, &retErr)

	if subject, ok := v.(string); ok {
		return &serviceLatency{
			subject:  subject,
			sampling: DEFAULT_SERVICE_LATENCY_SAMPLING,
		}, nil
	}

	latency, ok := v.(map[string]any)
	if !ok {
		return nil, &configErr{token: root,
			reason: fmt.Sprintf("Expected latency entry to be a map/struct or string, got %T", v)}
	}

	sl := serviceLatency{
		sampling: DEFAULT_SERVICE_LATENCY_SAMPLING,
	}

	// Read sampling value.
	if v, ok := latency["sampling"]; ok {
		tk, v := unwrapValue(v, &lt)
		header := false
		var sample int64
		switch vv := v.(type) {
		case int64:
			// Sample is an int, like 50.
			sample = vv
		case string:
			// Sample is a string, like "50%".
			if strings.ToLower(strings.TrimSpace(vv)) == "headers" {
				header = true
				sample = 0
				break
			}
			s := strings.TrimSuffix(vv, "%")
			n, err := strconv.Atoi(s)
			if err != nil {
				return nil, &configErr{token: tk,
					reason: fmt.Sprintf("Failed to parse latency sample: %v", err)}
			}
			sample = int64(n)
		default:
			return nil, &configErr{token: tk,
				reason: fmt.Sprintf("Expected latency sample to be a string or map/struct, got %T", v)}
		}
		if !header {
			if sample < 1 || sample > 100 {
				return nil, &configErr{token: tk,
					reason: ErrBadSampling.Error()}
			}
		}

		sl.sampling = int8(sample)
	}

	// Read subject value.
	v, ok = latency["subject"]
	if !ok {
		return nil, &configErr{token: root,
			reason: "Latency subject required, but missing"}
	}

	tk, v := unwrapValue(v, &lt)
	subject, ok := v.(string)
	if !ok {
		return nil, &configErr{token: tk,
			reason: fmt.Sprintf("Expected latency subject to be a string, got %T", subject)}
	}
	sl.subject = subject

	return &sl, nil
}

// Parse an import stream or service.
// e.g.
// {stream: {account: "synadia", subject:"public.synadia"}, prefix: "imports.synadia"}
// {stream: {account: "synadia", subject:"synadia.private.*"}}
// {service: {account: "synadia", subject: "pub.special.request"}, to: "synadia.request"}
func parseImportStreamOrService(v any, errors *[]error) (*importStream, *importService, error) {
	var (
		curStream  *importStream
		curService *importService
		pre, to    string
		share      bool
		lt         token
	)
	defer convertPanicToErrorList(&lt, errors)

	tk, mv := unwrapValue(v, &lt)
	vv, ok := mv.(map[string]any)
	if !ok {
		return nil, nil, &configErr{tk, fmt.Sprintf("Import Items should be a map with type entry, got %T", mv)}
	}
	for mk, mv := range vv {
		tk, mv := unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "stream":
			if curService != nil {
				err := &configErr{tk, "Detected stream but already saw a service"}
				*errors = append(*errors, err)
				continue
			}
			ac, ok := mv.(map[string]any)
			if !ok {
				err := &configErr{tk, fmt.Sprintf("Stream entry should be an account map, got %T", mv)}
				*errors = append(*errors, err)
				continue
			}
			// Make sure this is a map with account and subject
			accountName, subject, err := parseAccount(ac, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if accountName == _EMPTY_ || subject == _EMPTY_ {
				err := &configErr{tk, "Expect an account name and a subject"}
				*errors = append(*errors, err)
				continue
			}
			curStream = &importStream{an: accountName, sub: subject}
			if to != _EMPTY_ {
				curStream.to = to
			}
			if pre != _EMPTY_ {
				curStream.pre = pre
			}
		case "service":
			if curStream != nil {
				err := &configErr{tk, "Detected service but already saw a stream"}
				*errors = append(*errors, err)
				continue
			}
			ac, ok := mv.(map[string]interface{})
			if !ok {
				err := &configErr{tk, fmt.Sprintf("Service entry should be an account map, got %T", mv)}
				*errors = append(*errors, err)
				continue
			}
			// Make sure this is a map with account and subject
			accountName, subject, err := parseAccount(ac, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if accountName == _EMPTY_ || subject == _EMPTY_ {
				err := &configErr{tk, "Expect an account name and a subject"}
				*errors = append(*errors, err)
				continue
			}
			curService = &importService{an: accountName, sub: subject}
			if to != _EMPTY_ {
				curService.to = to
			} else {
				curService.to = subject
			}
			curService.share = share
		case "prefix":
			pre = mv.(string)
			if curStream != nil {
				curStream.pre = pre
			}
		case "to":
			to = mv.(string)
			if curService != nil {
				curService.to = to
			}
			if curStream != nil {
				curStream.to = to
				if curStream.pre != _EMPTY_ {
					err := &configErr{tk, "Stream import can not have a 'prefix' and a 'to' property"}
					*errors = append(*errors, err)
					continue
				}
			}
		case "share":
			share = mv.(bool)
			if curService != nil {
				curService.share = share
			}
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
			}
		}

	}
	return curStream, curService, nil
}

// Apply permission defaults to users/nkeyuser that don't have their own.
func applyDefaultPermissions(users []*User, nkeys []*NkeyUser, defaultP *Permissions) {
	if defaultP == nil {
		return
	}
	for _, user := range users {
		if user.Permissions == nil {
			user.Permissions = defaultP
		}
	}
	for _, user := range nkeys {
		if user.Permissions == nil {
			user.Permissions = defaultP
		}
	}
}

// Helper function to parse Authorization configs.
func parseAuthorization(v any, errors *[]error) (*authorization, error) {
	var (
		am   map[string]any
		tk   token
		lt   token
		auth = &authorization{}
	)
	defer convertPanicToErrorList(&lt, errors)

	_, v = unwrapValue(v, &lt)
	am = v.(map[string]any)
	for mk, mv := range am {
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "user", "username":
			auth.user = mv.(string)
		case "pass", "password":
			auth.pass = mv.(string)
		case "token":
			auth.token = mv.(string)
		case "timeout":
			at := float64(1)
			switch mv := mv.(type) {
			case int64:
				at = float64(mv)
			case float64:
				at = mv
			}
			auth.timeout = at
		case "users":
			nkeys, users, err := parseUsers(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			auth.users = users
			auth.nkeys = nkeys
		case "default_permission", "default_permissions", "permissions":
			permissions, err := parseUserPermissions(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			auth.defaultPermissions = permissions
		case "auth_callout", "auth_hook":
			ac, err := parseAuthCallout(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			auth.callout = ac
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
			}
			continue
		}

		applyDefaultPermissions(auth.users, auth.nkeys, auth.defaultPermissions)
	}
	return auth, nil
}

// Helper function to parse multiple users array with optional permissions.
func parseUsers(mv any, errors *[]error) ([]*NkeyUser, []*User, error) {
	var (
		tk    token
		lt    token
		keys  []*NkeyUser
		users = []*User{}
	)
	defer convertPanicToErrorList(&lt, errors)
	tk, mv = unwrapValue(mv, &lt)

	// Make sure we have an array
	uv, ok := mv.([]any)
	if !ok {
		return nil, nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)}
	}
	for _, u := range uv {
		tk, u = unwrapValue(u, &lt)

		// Check its a map/struct
		um, ok := u.(map[string]any)
		if !ok {
			err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)}
			*errors = append(*errors, err)
			continue
		}

		var (
			user  = &User{}
			nkey  = &NkeyUser{}
			perms *Permissions
			err   error
		)
		for k, v := range um {
			// Also needs to unwrap first
			tk, v = unwrapValue(v, &lt)

			switch strings.ToLower(k) {
			case "nkey":
				nkey.Nkey = v.(string)
			case "user", "username":
				user.Username = v.(string)
			case "pass", "password":
				user.Password = v.(string)
			case "permission", "permissions", "authorization":
				perms, err = parseUserPermissions(tk, errors)
				if err != nil {
					*errors = append(*errors, err)
					continue
				}
			case "allowed_connection_types", "connection_types", "clients":
				cts := parseAllowedConnectionTypes(tk, &lt, v, errors)
				nkey.AllowedConnectionTypes = cts
				user.AllowedConnectionTypes = cts
			default:
				if !tk.IsUsedVariable() {
					err := &unknownConfigFieldErr{
						field: k,
						configErr: configErr{
							token: tk,
						},
					}
					*errors = append(*errors, err)
					continue
				}
			}
		}
		// Place perms if we have them.
		if perms != nil {
			// nkey takes precedent.
			if nkey.Nkey != _EMPTY_ {
				nkey.Permissions = perms
			} else {
				user.Permissions = perms
			}
		}

		// Check to make sure we have at least an nkey or username <password> defined.
		if nkey.Nkey == _EMPTY_ && user.Username == _EMPTY_ {
			return nil, nil, &configErr{tk, "User entry requires a user"}
		} else if nkey.Nkey != _EMPTY_ {
			// Make sure the nkey a proper public nkey for a user..
			if !nkeys.IsValidPublicUserKey(nkey.Nkey) {
				return nil, nil, &configErr{tk, "Not a valid public nkey for a user"}
			}
			// If we have user or password defined here that is an error.
			if user.Username != _EMPTY_ || user.Password != _EMPTY_ {
				return nil, nil, &configErr{tk, "Nkey users do not take usernames or passwords"}
			}
			keys = append(keys, nkey)
		} else {
			users = append(users, user)
		}
	}
	return keys, users, nil
}

func parseAllowedConnectionTypes(tk token, lt *token, mv any, errors *[]error) map[string]struct{} {
	cts, err := parseStringArray("allowed connection types", tk, lt, mv, errors)
	// If error, it has already been added to the `errors` array, simply return
	if err != nil {
		return nil
	}
	m, err := convertAllowedConnectionTypes(cts)
	if err != nil {
		*errors = append(*errors, &configErr{tk, err.Error()})
	}
	return m
}

// Helper function to parse auth callouts.
func parseAuthCallout(mv any, errors *[]error) (*AuthCallout, error) {
	var (
		tk token
		lt token
		ac = &AuthCallout{}
	)
	defer convertPanicToErrorList(&lt, errors)

	tk, mv = unwrapValue(mv, &lt)
	pm, ok := mv.(map[string]any)
	if !ok {
		return nil, &configErr{tk, fmt.Sprintf("Expected authorization callout to be a map/struct, got %+v", mv)}
	}
	for k, v := range pm {
		tk, mv = unwrapValue(v, &lt)

		switch strings.ToLower(k) {
		case "issuer":
			ac.Issuer = mv.(string)
			if !nkeys.IsValidPublicAccountKey(ac.Issuer) {
				return nil, &configErr{tk, fmt.Sprintf("Expected callout user to be a valid public account nkey, got %q", ac.Issuer)}
			}
		case "account", "acc":
			ac.Account = mv.(string)
		case "auth_users", "users":
			aua, ok := mv.([]any)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("Expected auth_users field to be an array, got %T", v)}
			}
			for _, uv := range aua {
				_, uv = unwrapValue(uv, &lt)
				ac.AuthUsers = append(ac.AuthUsers, uv.(string))
			}
		case "xkey", "key":
			ac.XKey = mv.(string)
			if !nkeys.IsValidPublicCurveKey(ac.XKey) {
				return nil, &configErr{tk, fmt.Sprintf("Expected callout xkey to be a valid public xkey, got %q", ac.XKey)}
			}
		default:
			if !tk.IsUsedVariable() {
				err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing authorization callout", k)}
				*errors = append(*errors, err)
			}
		}
	}
	// Make sure we have all defined. All fields are required.
	// If no account specified, selet $G.
	if ac.Account == _EMPTY_ {
		ac.Account = globalAccountName
	}
	if ac.Issuer == _EMPTY_ {
		return nil, &configErr{tk, "Authorization callouts require an issuer to be specified"}
	}
	if len(ac.AuthUsers) == 0 {
		return nil, &configErr{tk, "Authorization callouts require authorized users to be specified"}
	}
	return ac, nil
}

// Helper function to parse user/account permissions
func parseUserPermissions(mv any, errors *[]error) (*Permissions, error) {
	var (
		tk token
		lt token
		p  = &Permissions{}
	)
	defer convertPanicToErrorList(&lt, errors)

	tk, mv = unwrapValue(mv, &lt)
	pm, ok := mv.(map[string]any)
	if !ok {
		return nil, &configErr{tk, fmt.Sprintf("Expected permissions to be a map/struct, got %+v", mv)}
	}
	for k, v := range pm {
		tk, mv = unwrapValue(v, &lt)

		switch strings.ToLower(k) {
		// For routes:
		// Import is Publish
		// Export is Subscribe
		case "pub", "publish", "import":
			perms, err := parseVariablePermissions(mv, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			p.Publish = perms
		case "sub", "subscribe", "export":
			perms, err := parseVariablePermissions(mv, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			p.Subscribe = perms
		case "publish_allow_responses", "allow_responses":
			rp := &ResponsePermission{
				MaxMsgs: DEFAULT_ALLOW_RESPONSE_MAX_MSGS,
				Expires: DEFAULT_ALLOW_RESPONSE_EXPIRATION,
			}
			// Try boolean first
			responses, ok := mv.(bool)
			if ok {
				if responses {
					p.Response = rp
				}
			} else {
				p.Response = parseAllowResponses(v, errors)
			}
			if p.Response != nil {
				if p.Publish == nil {
					p.Publish = &SubjectPermission{}
				}
				if p.Publish.Allow == nil {
					// We turn off the blanket allow statement.
					p.Publish.Allow = []string{}
				}
			}
		default:
			if !tk.IsUsedVariable() {
				err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing permissions", k)}
				*errors = append(*errors, err)
			}
		}
	}
	return p, nil
}

// Top level parser for authorization configurations.
func parseVariablePermissions(v any, errors *[]error) (*SubjectPermission, error) {
	switch vv := v.(type) {
	case map[string]any:
		// New style with allow and/or deny properties.
		return parseSubjectPermission(vv, errors)
	default:
		// Old style
		return parseOldPermissionStyle(v, errors)
	}
}

// Helper function to parse subject singletons and/or arrays
func parsePermSubjects(v any, errors *[]error) ([]string, error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)

	var subjects []string
	switch vv := v.(type) {
	case string:
		subjects = append(subjects, vv)
	case []string:
		subjects = vv
	case []any:
		for _, i := range vv {
			tk, i := unwrapValue(i, &lt)

			subject, ok := i.(string)
			if !ok {
				return nil, &configErr{tk, "Subject in permissions array cannot be cast to string"}
			}
			subjects = append(subjects, subject)
		}
	default:
		return nil, &configErr{tk, fmt.Sprintf("Expected subject permissions to be a subject, or array of subjects, got %T", v)}
	}
	if err := checkPermSubjectArray(subjects); err != nil {
		return nil, &configErr{tk, err.Error()}
	}
	return subjects, nil
}

// Helper function to parse a ResponsePermission.
func parseAllowResponses(v any, errors *[]error) *ResponsePermission {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	// Check if this is a map.
	pm, ok := v.(map[string]any)
	if !ok {
		err := &configErr{tk, "error parsing response permissions, expected a boolean or a map"}
		*errors = append(*errors, err)
		return nil
	}

	rp := &ResponsePermission{
		MaxMsgs: DEFAULT_ALLOW_RESPONSE_MAX_MSGS,
		Expires: DEFAULT_ALLOW_RESPONSE_EXPIRATION,
	}

	for k, v := range pm {
		tk, v = unwrapValue(v, &lt)
		switch strings.ToLower(k) {
		case "max", "max_msgs", "max_messages", "max_responses":
			max := int(v.(int64))
			// Negative values are accepted (mean infinite), and 0
			// means default value (set above).
			if max != 0 {
				rp.MaxMsgs = max
			}
		case "expires", "expiration", "ttl":
			wd, ok := v.(string)
			if ok {
				ttl, err := time.ParseDuration(wd)
				if err != nil {
					err := &configErr{tk, fmt.Sprintf("error parsing expires: %v", err)}
					*errors = append(*errors, err)
					return nil
				}
				// Negative values are accepted (mean infinite), and 0
				// means default value (set above).
				if ttl != 0 {
					rp.Expires = ttl
				}
			} else {
				err := &configErr{tk, "error parsing expires, not a duration string"}
				*errors = append(*errors, err)
				return nil
			}
		default:
			if !tk.IsUsedVariable() {
				err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing permissions", k)}
				*errors = append(*errors, err)
			}
		}
	}
	return rp
}

// Helper function to parse old style authorization configs.
func parseOldPermissionStyle(v any, errors *[]error) (*SubjectPermission, error) {
	subjects, err := parsePermSubjects(v, errors)
	if err != nil {
		return nil, err
	}
	return &SubjectPermission{Allow: subjects}, nil
}

// Helper function to parse new style authorization into a SubjectPermission with Allow and Deny.
func parseSubjectPermission(v any, errors *[]error) (*SubjectPermission, error) {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	m := v.(map[string]any)
	if len(m) == 0 {
		return nil, nil
	}
	p := &SubjectPermission{}
	for k, v := range m {
		tk, _ := unwrapValue(v, &lt)
		switch strings.ToLower(k) {
		case "allow":
			subjects, err := parsePermSubjects(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			p.Allow = subjects
		case "deny":
			subjects, err := parsePermSubjects(tk, errors)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			p.Deny = subjects
		default:
			if !tk.IsUsedVariable() {
				err := &configErr{tk, fmt.Sprintf("Unknown field name %q parsing subject permissions, only 'allow' or 'deny' are permitted", k)}
				*errors = append(*errors, err)
			}
		}
	}
	return p, nil
}

// Helper function to validate permissions subjects.
func checkPermSubjectArray(sa []string) error {
	for _, s := range sa {
		if !IsValidSubject(s) {
			// Check here if this is a queue group qualified subject.
			elements := strings.Fields(s)
			if len(elements) != 2 {
				return fmt.Errorf("subject %q is not a valid subject", s)
			} else if !IsValidSubject(elements[0]) {
				return fmt.Errorf("subject %q is not a valid subject", elements[0])
			}
		}
	}
	return nil
}

// PrintTLSHelpAndDie prints TLS usage and exits.
func PrintTLSHelpAndDie() {
	fmt.Printf("%s", tlsUsage)
	for k := range cipherMap {
		fmt.Printf("    %s\n", k)
	}
	fmt.Printf("\nAvailable curve preferences include:\n")
	for k := range curvePreferenceMap {
		fmt.Printf("    %s\n", k)
	}
	if runtime.GOOS == "windows" {
		fmt.Printf("%s\n", certstore.Usage)
	}
	fmt.Printf("%s", certidp.OCSPPeerUsage)
	fmt.Printf("%s", OCSPResponseCacheUsage)
	os.Exit(0)
}

func parseCipher(cipherName string) (uint16, error) {
	cipher, exists := cipherMap[cipherName]
	if !exists {
		return 0, fmt.Errorf("unrecognized cipher %s", cipherName)
	}

	return cipher, nil
}

func parseCurvePreferences(curveName string) (tls.CurveID, error) {
	curve, exists := curvePreferenceMap[curveName]
	if !exists {
		return 0, fmt.Errorf("unrecognized curve preference %s", curveName)
	}
	return curve, nil
}

func parseTLSVersion(v any) (uint16, error) {
	var tlsVersionNumber uint16
	switch v := v.(type) {
	case string:
		n, err := tlsVersionFromString(v)
		if err != nil {
			return 0, err
		}
		tlsVersionNumber = n
	default:
		return 0, fmt.Errorf("'min_version' wrong type: %v", v)
	}
	if tlsVersionNumber < tls.VersionTLS12 {
		return 0, fmt.Errorf("unsupported TLS version: %s", tls.VersionName(tlsVersionNumber))
	}
	return tlsVersionNumber, nil
}

// Helper function to parse TLS configs.
func parseTLS(v any, isClientCtx bool) (t *TLSConfigOpts, retErr error) {
	var (
		tlsm map[string]any
		tc   = TLSConfigOpts{}
		lt   token
	)
	defer convertPanicToError(&lt, &retErr)

	tk, v := unwrapValue(v, &lt)
	tlsm = v.(map[string]any)
	for mk, mv := range tlsm {
		tk, mv := unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "cert_file":
			certFile, ok := mv.(string)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'cert_file' to be filename"}
			}
			tc.CertFile = certFile
		case "key_file":
			keyFile, ok := mv.(string)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'key_file' to be filename"}
			}
			tc.KeyFile = keyFile
		case "ca_file":
			caFile, ok := mv.(string)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'ca_file' to be filename"}
			}
			tc.CaFile = caFile
		case "insecure":
			insecure, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'insecure' to be a boolean"}
			}
			tc.Insecure = insecure
		case "verify":
			verify, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'verify' to be a boolean"}
			}
			tc.Verify = verify
		case "verify_and_map":
			verify, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'verify_and_map' to be a boolean"}
			}
			if verify {
				tc.Verify = verify
			}
			tc.Map = verify
		case "verify_cert_and_check_known_urls":
			verify, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'verify_cert_and_check_known_urls' to be a boolean"}
			}
			if verify && isClientCtx {
				return nil, &configErr{tk, "verify_cert_and_check_known_urls not supported in this context"}
			}
			if verify {
				tc.Verify = verify
			}
			tc.TLSCheckKnownURLs = verify
		case "cipher_suites":
			ra := mv.([]any)
			if len(ra) == 0 {
				return nil, &configErr{tk, "error parsing tls config, 'cipher_suites' cannot be empty"}
			}
			tc.Ciphers = make([]uint16, 0, len(ra))
			for _, r := range ra {
				tk, r := unwrapValue(r, &lt)
				cipher, err := parseCipher(r.(string))
				if err != nil {
					return nil, &configErr{tk, err.Error()}
				}
				tc.Ciphers = append(tc.Ciphers, cipher)
			}
		case "curve_preferences":
			ra := mv.([]any)
			if len(ra) == 0 {
				return nil, &configErr{tk, "error parsing tls config, 'curve_preferences' cannot be empty"}
			}
			tc.CurvePreferences = make([]tls.CurveID, 0, len(ra))
			for _, r := range ra {
				tk, r := unwrapValue(r, &lt)
				cps, err := parseCurvePreferences(r.(string))
				if err != nil {
					return nil, &configErr{tk, err.Error()}
				}
				tc.CurvePreferences = append(tc.CurvePreferences, cps)
			}
		case "timeout":
			at := float64(0)
			switch mv := mv.(type) {
			case int64:
				at = float64(mv)
			case float64:
				at = mv
			case string:
				d, err := time.ParseDuration(mv)
				if err != nil {
					return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, 'timeout' %s", err)}
				}
				at = d.Seconds()
			default:
				return nil, &configErr{tk, "error parsing tls config, 'timeout' wrong type"}
			}
			tc.Timeout = at
		case "connection_rate_limit":
			at := int64(0)
			switch mv := mv.(type) {
			case int64:
				at = mv
			default:
				return nil, &configErr{tk, "error parsing tls config, 'connection_rate_limit' wrong type"}
			}
			tc.RateLimit = at
		case "pinned_certs":
			ra, ok := mv.([]any)
			if !ok {
				return nil, &configErr{tk, "error parsing tls config, expected 'pinned_certs' to be a list of hex-encoded sha256 of DER encoded SubjectPublicKeyInfo"}
			}
			if len(ra) != 0 {
				wl := PinnedCertSet{}
				re := regexp.MustCompile("^[A-Fa-f0-9]{64}$")
				for _, r := range ra {
					tk, r := unwrapValue(r, &lt)
					entry := strings.ToLower(r.(string))
					if !re.MatchString(entry) {
						return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, 'pinned_certs' key %s does not look like hex-encoded sha256 of DER encoded SubjectPublicKeyInfo", entry)}
					}
					wl[entry] = struct{}{}
				}
				tc.PinnedCerts = wl
			}
		case "cert_store":
			certStore, ok := mv.(string)
			if !ok || certStore == _EMPTY_ {
				return nil, &configErr{tk, certstore.ErrBadCertStoreField.Error()}
			}
			certStoreType, err := certstore.ParseCertStore(certStore)
			if err != nil {
				return nil, &configErr{tk, err.Error()}
			}
			tc.CertStore = certStoreType
		case "cert_match_by":
			certMatchBy, ok := mv.(string)
			if !ok || certMatchBy == _EMPTY_ {
				return nil, &configErr{tk, certstore.ErrBadCertMatchByField.Error()}
			}
			certMatchByType, err := certstore.ParseCertMatchBy(certMatchBy)
			if err != nil {
				return nil, &configErr{tk, err.Error()}
			}
			tc.CertMatchBy = certMatchByType
		case "cert_match":
			certMatch, ok := mv.(string)
			if !ok || certMatch == _EMPTY_ {
				return nil, &configErr{tk, certstore.ErrBadCertMatchField.Error()}
			}
			tc.CertMatch = certMatch
		case "ca_certs_match":
			rv := []string{}
			switch mv := mv.(type) {
			case string:
				rv = append(rv, mv)
			case []string:
				rv = append(rv, mv...)
			case []interface{}:
				for _, t := range mv {
					if token, ok := t.(token); ok {
						if ts, ok := token.Value().(string); ok {
							rv = append(rv, ts)
							continue
						} else {
							return nil, &configErr{tk, fmt.Sprintf("error parsing ca_cert_match: unsupported type %T where string is expected", token)}
						}
					} else {
						return nil, &configErr{tk, fmt.Sprintf("error parsing ca_cert_match: unsupported type %T", t)}
					}
				}
			}
			tc.CaCertsMatch = rv
		case "handshake_first", "first", "immediate":
			switch mv := mv.(type) {
			case bool:
				tc.HandshakeFirst = mv
			case string:
				switch strings.ToLower(mv) {
				case "true", "on":
					tc.HandshakeFirst = true
				case "false", "off":
					tc.HandshakeFirst = false
				case "auto", "auto_fallback":
					tc.HandshakeFirst = true
					tc.FallbackDelay = DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY
				default:
					// Check to see if this is a duration.
					if dur, err := time.ParseDuration(mv); err == nil {
						tc.HandshakeFirst = true
						tc.FallbackDelay = dur
						break
					}
					return nil, &configErr{tk, fmt.Sprintf("field %q's value %q is invalid", mk, mv)}
				}
			default:
				return nil, &configErr{tk, fmt.Sprintf("field %q should be a boolean or a string, got %T", mk, mv)}
			}
		case "cert_match_skip_invalid":
			certMatchSkipInvalid, ok := mv.(bool)
			if !ok {
				return nil, &configErr{tk, certstore.ErrBadCertMatchSkipInvalidField.Error()}
			}
			tc.CertMatchSkipInvalid = certMatchSkipInvalid
		case "ocsp_peer":
			switch vv := mv.(type) {
			case bool:
				pc := certidp.NewOCSPPeerConfig()
				if vv {
					// Set enabled
					pc.Verify = true
					tc.OCSPPeerConfig = pc
				} else {
					// Set disabled
					pc.Verify = false
					tc.OCSPPeerConfig = pc
				}
			case map[string]any:
				pc, err := parseOCSPPeer(mv)
				if err != nil {
					return nil, &configErr{tk, err.Error()}
				}
				tc.OCSPPeerConfig = pc
			default:
				return nil, &configErr{tk, fmt.Sprintf("error parsing ocsp peer config: unsupported type %T", v)}
			}
		case "certs", "certificates":
			certs, ok := mv.([]any)
			if !ok {
				return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", v)}
			}
			tc.Certificates = make([]*TLSCertPairOpt, len(certs))
			for i, v := range certs {
				tk, vv := unwrapValue(v, &lt)
				pair, ok := vv.(map[string]any)
				if !ok {
					return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", vv)}
				}
				certPair := &TLSCertPairOpt{}
				for k, v := range pair {
					tk, vv = unwrapValue(v, &lt)
					file, ok := vv.(string)
					if !ok {
						return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", vv)}
					}
					switch k {
					case "cert_file":
						certPair.CertFile = file
					case "key_file":
						certPair.KeyFile = file
					default:
						return nil, &configErr{tk, fmt.Sprintf("error parsing tls certs config, unknown field %q", k)}
					}
				}
				if certPair.CertFile == _EMPTY_ || certPair.KeyFile == _EMPTY_ {
					return nil, &configErr{tk, "error parsing certificates config: both 'cert_file' and 'cert_key' options are required"}
				}
				tc.Certificates[i] = certPair
			}
		case "min_version":
			minVersion, err := parseTLSVersion(mv)
			if err != nil {
				return nil, &configErr{tk, fmt.Sprintf("error parsing tls config: %v", err)}
			}
			tc.MinVersion = minVersion
		default:
			return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, unknown field %q", mk)}
		}
	}
	if len(tc.Certificates) > 0 && tc.CertFile != _EMPTY_ {
		return nil, &configErr{tk, "error parsing tls config, cannot combine 'cert_file' option with 'certs' option"}
	}

	// If cipher suites were not specified then use the defaults
	if tc.Ciphers == nil {
		tc.Ciphers = defaultCipherSuites()
	}

	// If curve preferences were not specified, then use the defaults
	if tc.CurvePreferences == nil {
		tc.CurvePreferences = defaultCurvePreferences()
	}

	return &tc, nil
}

func parseSimpleAuth(v any, errors *[]error) *authorization {
	var (
		am   map[string]any
		tk   token
		lt   token
		auth = &authorization{}
	)
	defer convertPanicToErrorList(&lt, errors)

	_, v = unwrapValue(v, &lt)
	am = v.(map[string]any)
	for mk, mv := range am {
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "user", "username":
			auth.user = mv.(string)
		case "pass", "password":
			auth.pass = mv.(string)
		case "token":
			auth.token = mv.(string)
		case "timeout":
			at := float64(1)
			switch mv := mv.(type) {
			case int64:
				at = float64(mv)
			case float64:
				at = mv
			}
			auth.timeout = at
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
			}
			continue
		}
	}
	return auth
}

func parseStringArray(fieldName string, tk token, lt *token, mv any, errors *[]error) ([]string, error) {
	switch mv := mv.(type) {
	case string:
		return []string{mv}, nil
	case []any:
		strs := make([]string, 0, len(mv))
		for _, val := range mv {
			tk, val = unwrapValue(val, lt)
			if str, ok := val.(string); ok {
				strs = append(strs, str)
			} else {
				err := &configErr{tk, fmt.Sprintf("error parsing %s: unsupported type in array %T", fieldName, val)}
				*errors = append(*errors, err)
				continue
			}
		}
		return strs, nil
	default:
		err := &configErr{tk, fmt.Sprintf("error parsing %s: unsupported type %T", fieldName, mv)}
		*errors = append(*errors, err)
		return nil, err
	}
}

func parseWebsocket(v any, o *Options, errors *[]error) error {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	gm, ok := v.(map[string]any)
	if !ok {
		return &configErr{tk, fmt.Sprintf("Expected websocket to be a map, got %T", v)}
	}
	for mk, mv := range gm {
		// Again, unwrap token value if line check is required.
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "listen":
			hp, err := parseListen(mv)
			if err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			o.Websocket.Host = hp.host
			o.Websocket.Port = hp.port
		case "port":
			o.Websocket.Port = int(mv.(int64))
		case "host", "net":
			o.Websocket.Host = mv.(string)
		case "advertise":
			o.Websocket.Advertise = mv.(string)
		case "no_tls":
			o.Websocket.NoTLS = mv.(bool)
		case "tls":
			tc, err := parseTLS(tk, true)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if o.Websocket.TLSConfig, err = GenTLSConfig(tc); err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			o.Websocket.TLSMap = tc.Map
			o.Websocket.TLSPinnedCerts = tc.PinnedCerts
			o.Websocket.tlsConfigOpts = tc
		case "same_origin":
			o.Websocket.SameOrigin = mv.(bool)
		case "allowed_origins", "allowed_origin", "allow_origins", "allow_origin", "origins", "origin":
			o.Websocket.AllowedOrigins, _ = parseStringArray("allowed origins", tk, &lt, mv, errors)
		case "handshake_timeout":
			ht := time.Duration(0)
			switch mv := mv.(type) {
			case int64:
				ht = time.Duration(mv) * time.Second
			case string:
				var err error
				ht, err = time.ParseDuration(mv)
				if err != nil {
					err := &configErr{tk, err.Error()}
					*errors = append(*errors, err)
					continue
				}
			default:
				err := &configErr{tk, fmt.Sprintf("error parsing handshake timeout: unsupported type %T", mv)}
				*errors = append(*errors, err)
			}
			o.Websocket.HandshakeTimeout = ht
		case "compress", "compression":
			o.Websocket.Compression = mv.(bool)
		case "authorization", "authentication":
			auth := parseSimpleAuth(tk, errors)
			o.Websocket.Username = auth.user
			o.Websocket.Password = auth.pass
			o.Websocket.Token = auth.token
			o.Websocket.AuthTimeout = auth.timeout
		case "jwt_cookie":
			o.Websocket.JWTCookie = mv.(string)
		case "no_auth_user":
			o.Websocket.NoAuthUser = mv.(string)
		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
				continue
			}
		}
	}
	return nil
}

func parseMQTT(v any, o *Options, errors *[]error, warnings *[]error) error {
	var lt token
	defer convertPanicToErrorList(&lt, errors)

	tk, v := unwrapValue(v, &lt)
	gm, ok := v.(map[string]any)
	if !ok {
		return &configErr{tk, fmt.Sprintf("Expected mqtt to be a map, got %T", v)}
	}
	for mk, mv := range gm {
		// Again, unwrap token value if line check is required.
		tk, mv = unwrapValue(mv, &lt)
		switch strings.ToLower(mk) {
		case "listen":
			hp, err := parseListen(mv)
			if err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			o.MQTT.Host = hp.host
			o.MQTT.Port = hp.port
		case "port":
			o.MQTT.Port = int(mv.(int64))
		case "host", "net":
			o.MQTT.Host = mv.(string)
		case "tls":
			tc, err := parseTLS(tk, true)
			if err != nil {
				*errors = append(*errors, err)
				continue
			}
			if o.MQTT.TLSConfig, err = GenTLSConfig(tc); err != nil {
				err := &configErr{tk, err.Error()}
				*errors = append(*errors, err)
				continue
			}
			o.MQTT.TLSTimeout = tc.Timeout
			o.MQTT.TLSMap = tc.Map
			o.MQTT.TLSPinnedCerts = tc.PinnedCerts
			o.MQTT.tlsConfigOpts = tc
		case "authorization", "authentication":
			auth := parseSimpleAuth(tk, errors)
			o.MQTT.Username = auth.user
			o.MQTT.Password = auth.pass
			o.MQTT.Token = auth.token
			o.MQTT.AuthTimeout = auth.timeout
		case "no_auth_user":
			o.MQTT.NoAuthUser = mv.(string)
		case "ack_wait", "ackwait":
			o.MQTT.AckWait = parseDuration("ack_wait", tk, mv, errors, warnings)
		case "max_ack_pending", "max_pending", "max_inflight":
			tmp := int(mv.(int64))
			if tmp < 0 || tmp > 0xFFFF {
				err := &configErr{tk, fmt.Sprintf("invalid value %v, should in [0..%d] range", tmp, 0xFFFF)}
				*errors = append(*errors, err)
			} else {
				o.MQTT.MaxAckPending = uint16(tmp)
			}
		case "js_domain":
			o.MQTT.JsDomain = mv.(string)
		case "stream_replicas":
			o.MQTT.StreamReplicas = int(mv.(int64))
		case "consumer_replicas":
			err := &configWarningErr{
				field: mk,
				configErr: configErr{
					token:  tk,
					reason: `consumer replicas setting ignored in this server version`,
				},
			}
			*warnings = append(*warnings, err)
		case "consumer_memory_storage":
			o.MQTT.ConsumerMemoryStorage = mv.(bool)
		case "consumer_inactive_threshold", "consumer_auto_cleanup":
			o.MQTT.ConsumerInactiveThreshold = parseDuration("consumer_inactive_threshold", tk, mv, errors, warnings)

		case "reject_qos2_publish":
			o.MQTT.rejectQoS2Pub = mv.(bool)
		case "downgrade_qos2_subscribe":
			o.MQTT.downgradeQoS2Sub = mv.(bool)

		default:
			if !tk.IsUsedVariable() {
				err := &unknownConfigFieldErr{
					field: mk,
					configErr: configErr{
						token: tk,
					},
				}
				*errors = append(*errors, err)
				continue
			}
		}
	}
	return nil
}

// GenTLSConfig loads TLS related configuration parameters.
func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) {
	// Create the tls.Config from our options before including the certs.
	// It will determine the cipher suites that we prefer.
	// FIXME(dlc) change if ARM based.
	config := tls.Config{
		MinVersion:               tls.VersionTLS12,
		CipherSuites:             tc.Ciphers,
		PreferServerCipherSuites: true,
		CurvePreferences:         tc.CurvePreferences,
		InsecureSkipVerify:       tc.Insecure,
	}

	switch {
	case tc.CertFile != _EMPTY_ && tc.CertStore != certstore.STOREEMPTY:
		return nil, certstore.ErrConflictCertFileAndStore
	case tc.CertFile != _EMPTY_ && tc.KeyFile == _EMPTY_:
		return nil, fmt.Errorf("missing 'key_file' in TLS configuration")
	case tc.CertFile == _EMPTY_ && tc.KeyFile != _EMPTY_:
		return nil, fmt.Errorf("missing 'cert_file' in TLS configuration")
	case tc.CertFile != _EMPTY_ && tc.KeyFile != _EMPTY_:
		// Now load in cert and private key
		cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile)
		if err != nil {
			return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
		}
		cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
		if err != nil {
			return nil, fmt.Errorf("error parsing certificate: %v", err)
		}
		config.Certificates = []tls.Certificate{cert}
	case tc.CertStore != certstore.STOREEMPTY:
		err := certstore.TLSConfig(tc.CertStore, tc.CertMatchBy, tc.CertMatch, tc.CaCertsMatch, tc.CertMatchSkipInvalid, &config)
		if err != nil {
			return nil, err
		}
	case tc.Certificates != nil:
		// Multiple certificate support.
		config.Certificates = make([]tls.Certificate, len(tc.Certificates))
		for i, certPair := range tc.Certificates {
			cert, err := tls.LoadX509KeyPair(certPair.CertFile, certPair.KeyFile)
			if err != nil {
				return nil, fmt.Errorf("error parsing X509 certificate/key pair %d/%d: %v", i+1, len(tc.Certificates), err)
			}
			cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
			if err != nil {
				return nil, fmt.Errorf("error parsing certificate %d/%d: %v", i+1, len(tc.Certificates), err)
			}
			config.Certificates[i] = cert
		}
	}

	// Require client certificates as needed
	if tc.Verify {
		config.ClientAuth = tls.RequireAndVerifyClientCert
	}
	// Add in CAs if applicable.
	if tc.CaFile != _EMPTY_ {
		rootPEM, err := os.ReadFile(tc.CaFile)
		if err != nil || rootPEM == nil {
			return nil, err
		}
		pool := x509.NewCertPool()
		ok := pool.AppendCertsFromPEM(rootPEM)
		if !ok {
			return nil, fmt.Errorf("failed to parse root ca certificate")
		}
		config.ClientCAs = pool
	}
	// Allow setting TLS minimum version.
	if tc.MinVersion > 0 {
		if tc.MinVersion < tls.VersionTLS12 {
			return nil, fmt.Errorf("unsupported minimum TLS version: %s", tls.VersionName(tc.MinVersion))
		}
		config.MinVersion = tc.MinVersion
	}

	return &config, nil
}

// MergeOptions will merge two options giving preference to the flagOpts
// if the item is present.
func MergeOptions(fileOpts, flagOpts *Options) *Options {
	if fileOpts == nil {
		return flagOpts
	}
	if flagOpts == nil {
		return fileOpts
	}
	// Merge the two, flagOpts override
	opts := *fileOpts

	if flagOpts.Port != 0 {
		opts.Port = flagOpts.Port
	}
	if flagOpts.Host != _EMPTY_ {
		opts.Host = flagOpts.Host
	}
	if flagOpts.DontListen {
		opts.DontListen = flagOpts.DontListen
	}
	if flagOpts.ClientAdvertise != _EMPTY_ {
		opts.ClientAdvertise = flagOpts.ClientAdvertise
	}
	if flagOpts.Username != _EMPTY_ {
		opts.Username = flagOpts.Username
	}
	if flagOpts.Password != _EMPTY_ {
		opts.Password = flagOpts.Password
	}
	if flagOpts.Authorization != _EMPTY_ {
		opts.Authorization = flagOpts.Authorization
	}
	if flagOpts.HTTPPort != 0 {
		opts.HTTPPort = flagOpts.HTTPPort
	}
	if flagOpts.HTTPBasePath != _EMPTY_ {
		opts.HTTPBasePath = flagOpts.HTTPBasePath
	}
	if flagOpts.Debug {
		opts.Debug = true
	}
	if flagOpts.Trace {
		opts.Trace = true
	}
	if flagOpts.Logtime {
		opts.Logtime = true
	}
	if flagOpts.LogFile != _EMPTY_ {
		opts.LogFile = flagOpts.LogFile
	}
	if flagOpts.PidFile != _EMPTY_ {
		opts.PidFile = flagOpts.PidFile
	}
	if flagOpts.PortsFileDir != _EMPTY_ {
		opts.PortsFileDir = flagOpts.PortsFileDir
	}
	if flagOpts.ProfPort != 0 {
		opts.ProfPort = flagOpts.ProfPort
	}
	if flagOpts.Cluster.ListenStr != _EMPTY_ {
		opts.Cluster.ListenStr = flagOpts.Cluster.ListenStr
	}
	if flagOpts.Cluster.NoAdvertise {
		opts.Cluster.NoAdvertise = true
	}
	if flagOpts.Cluster.ConnectRetries != 0 {
		opts.Cluster.ConnectRetries = flagOpts.Cluster.ConnectRetries
	}
	if flagOpts.Cluster.Advertise != _EMPTY_ {
		opts.Cluster.Advertise = flagOpts.Cluster.Advertise
	}
	if flagOpts.RoutesStr != _EMPTY_ {
		mergeRoutes(&opts, flagOpts)
	}
	if flagOpts.JetStream {
		fileOpts.JetStream = flagOpts.JetStream
	}
	return &opts
}

// RoutesFromStr parses route URLs from a string
func RoutesFromStr(routesStr string) []*url.URL {
	routes := strings.Split(routesStr, ",")
	if len(routes) == 0 {
		return nil
	}
	routeUrls := []*url.URL{}
	for _, r := range routes {
		r = strings.TrimSpace(r)
		u, _ := url.Parse(r)
		routeUrls = append(routeUrls, u)
	}
	return routeUrls
}

// This will merge the flag routes and override anything that was present.
func mergeRoutes(opts, flagOpts *Options) {
	routeUrls := RoutesFromStr(flagOpts.RoutesStr)
	if routeUrls == nil {
		return
	}
	opts.Routes = routeUrls
	opts.RoutesStr = flagOpts.RoutesStr
}

// RemoveSelfReference removes this server from an array of routes
func RemoveSelfReference(clusterPort int, routes []*url.URL) ([]*url.URL, error) {
	var cleanRoutes []*url.URL
	cport := strconv.Itoa(clusterPort)

	selfIPs, err := getInterfaceIPs()
	if err != nil {
		return nil, err
	}
	for _, r := range routes {
		host, port, err := net.SplitHostPort(r.Host)
		if err != nil {
			return nil, err
		}

		ipList, err := getURLIP(host)
		if err != nil {
			return nil, err
		}
		if cport == port && isIPInList(selfIPs, ipList) {
			continue
		}
		cleanRoutes = append(cleanRoutes, r)
	}

	return cleanRoutes, nil
}

func isIPInList(list1 []net.IP, list2 []net.IP) bool {
	for _, ip1 := range list1 {
		for _, ip2 := range list2 {
			if ip1.Equal(ip2) {
				return true
			}
		}
	}
	return false
}

func getURLIP(ipStr string) ([]net.IP, error) {
	ipList := []net.IP{}

	ip := net.ParseIP(ipStr)
	if ip != nil {
		ipList = append(ipList, ip)
		return ipList, nil
	}

	hostAddr, err := net.LookupHost(ipStr)
	if err != nil {
		return nil, fmt.Errorf("Error looking up host with route hostname: %v", err)
	}
	for _, addr := range hostAddr {
		ip = net.ParseIP(addr)
		if ip != nil {
			ipList = append(ipList, ip)
		}
	}
	return ipList, nil
}

func getInterfaceIPs() ([]net.IP, error) {
	var localIPs []net.IP

	interfaceAddr, err := net.InterfaceAddrs()
	if err != nil {
		return nil, fmt.Errorf("Error getting self referencing address: %v", err)
	}

	for i := 0; i < len(interfaceAddr); i++ {
		interfaceIP, _, _ := net.ParseCIDR(interfaceAddr[i].String())
		if net.ParseIP(interfaceIP.String()) != nil {
			localIPs = append(localIPs, interfaceIP)
		} else {
			return nil, fmt.Errorf("Error parsing self referencing address: %v", err)
		}
	}
	return localIPs, nil
}

func setBaselineOptions(opts *Options) {
	// Setup non-standard Go defaults
	if opts.Host == _EMPTY_ {
		opts.Host = DEFAULT_HOST
	}
	if opts.HTTPHost == _EMPTY_ {
		// Default to same bind from server if left undefined
		opts.HTTPHost = opts.Host
	}
	if opts.Port == 0 {
		opts.Port = DEFAULT_PORT
	} else if opts.Port == RANDOM_PORT {
		// Choose randomly inside of net.Listen
		opts.Port = 0
	}
	if opts.MaxConn == 0 {
		opts.MaxConn = DEFAULT_MAX_CONNECTIONS
	}
	if opts.PingInterval == 0 {
		opts.PingInterval = DEFAULT_PING_INTERVAL
	}
	if opts.MaxPingsOut == 0 {
		opts.MaxPingsOut = DEFAULT_PING_MAX_OUT
	}
	if opts.TLSTimeout == 0 {
		opts.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
	}
	if opts.AuthTimeout == 0 {
		opts.AuthTimeout = getDefaultAuthTimeout(opts.TLSConfig, opts.TLSTimeout)
	}
	if opts.Cluster.Port != 0 || opts.Cluster.ListenStr != _EMPTY_ {
		if opts.Cluster.Host == _EMPTY_ {
			opts.Cluster.Host = DEFAULT_HOST
		}
		if opts.Cluster.TLSTimeout == 0 {
			opts.Cluster.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
		}
		if opts.Cluster.AuthTimeout == 0 {
			opts.Cluster.AuthTimeout = getDefaultAuthTimeout(opts.Cluster.TLSConfig, opts.Cluster.TLSTimeout)
		}
		if opts.Cluster.PoolSize == 0 {
			opts.Cluster.PoolSize = DEFAULT_ROUTE_POOL_SIZE
		}
		// Unless pooling/accounts are disabled (by PoolSize being set to -1),
		// check for Cluster.Accounts. Add the system account if not present and
		// unless we have a configuration that disabled it.
		if opts.Cluster.PoolSize > 0 {
			sysAccName := opts.SystemAccount
			if sysAccName == _EMPTY_ && !opts.NoSystemAccount {
				sysAccName = DEFAULT_SYSTEM_ACCOUNT
			}
			if sysAccName != _EMPTY_ {
				var found bool
				for _, acc := range opts.Cluster.PinnedAccounts {
					if acc == sysAccName {
						found = true
						break
					}
				}
				if !found {
					opts.Cluster.PinnedAccounts = append(opts.Cluster.PinnedAccounts, sysAccName)
				}
			}
		}
		// Default to compression "accept", which means that compression is not
		// initiated, but if the remote selects compression, this server will
		// use the same.
		if c := &opts.Cluster.Compression; c.Mode == _EMPTY_ {
			if testDefaultClusterCompression != _EMPTY_ {
				c.Mode = testDefaultClusterCompression
			} else {
				c.Mode = CompressionAccept
			}
		}
	}
	if opts.LeafNode.Port != 0 {
		if opts.LeafNode.Host == _EMPTY_ {
			opts.LeafNode.Host = DEFAULT_HOST
		}
		if opts.LeafNode.TLSTimeout == 0 {
			opts.LeafNode.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
		}
		if opts.LeafNode.AuthTimeout == 0 {
			opts.LeafNode.AuthTimeout = getDefaultAuthTimeout(opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout)
		}
		// Default to compression "s2_auto".
		if c := &opts.LeafNode.Compression; c.Mode == _EMPTY_ {
			if testDefaultLeafNodeCompression != _EMPTY_ {
				c.Mode = testDefaultLeafNodeCompression
			} else {
				c.Mode = CompressionS2Auto
			}
		}
	}
	// Set baseline connect port for remotes.
	for _, r := range opts.LeafNode.Remotes {
		if r != nil {
			for _, u := range r.URLs {
				if u.Port() == _EMPTY_ {
					u.Host = net.JoinHostPort(u.Host, strconv.Itoa(DEFAULT_LEAFNODE_PORT))
				}
			}
			// Default to compression "s2_auto".
			if c := &r.Compression; c.Mode == _EMPTY_ {
				if testDefaultLeafNodeCompression != _EMPTY_ {
					c.Mode = testDefaultLeafNodeCompression
				} else {
					c.Mode = CompressionS2Auto
				}
			}
			// Set default first info timeout value if not set.
			if r.FirstInfoTimeout <= 0 {
				r.FirstInfoTimeout = DEFAULT_LEAFNODE_INFO_WAIT
			}
		}
	}

	// Set this regardless of opts.LeafNode.Port
	if opts.LeafNode.ReconnectInterval == 0 {
		opts.LeafNode.ReconnectInterval = DEFAULT_LEAF_NODE_RECONNECT
	}

	if opts.MaxControlLine == 0 {
		opts.MaxControlLine = MAX_CONTROL_LINE_SIZE
	}
	if opts.MaxPayload == 0 {
		opts.MaxPayload = MAX_PAYLOAD_SIZE
	}
	if opts.MaxPending == 0 {
		opts.MaxPending = MAX_PENDING_SIZE
	}
	if opts.WriteDeadline == time.Duration(0) {
		opts.WriteDeadline = DEFAULT_FLUSH_DEADLINE
	}
	if opts.MaxClosedClients == 0 {
		opts.MaxClosedClients = DEFAULT_MAX_CLOSED_CLIENTS
	}
	if opts.LameDuckDuration == 0 {
		opts.LameDuckDuration = DEFAULT_LAME_DUCK_DURATION
	}
	if opts.LameDuckGracePeriod == 0 {
		opts.LameDuckGracePeriod = DEFAULT_LAME_DUCK_GRACE_PERIOD
	}
	if opts.Gateway.Port != 0 {
		if opts.Gateway.Host == _EMPTY_ {
			opts.Gateway.Host = DEFAULT_HOST
		}
		if opts.Gateway.TLSTimeout == 0 {
			opts.Gateway.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
		}
		if opts.Gateway.AuthTimeout == 0 {
			opts.Gateway.AuthTimeout = getDefaultAuthTimeout(opts.Gateway.TLSConfig, opts.Gateway.TLSTimeout)
		}
	}
	if opts.ConnectErrorReports == 0 {
		opts.ConnectErrorReports = DEFAULT_CONNECT_ERROR_REPORTS
	}
	if opts.ReconnectErrorReports == 0 {
		opts.ReconnectErrorReports = DEFAULT_RECONNECT_ERROR_REPORTS
	}
	if opts.Websocket.Port != 0 {
		if opts.Websocket.Host == _EMPTY_ {
			opts.Websocket.Host = DEFAULT_HOST
		}
	}
	if opts.MQTT.Port != 0 {
		if opts.MQTT.Host == _EMPTY_ {
			opts.MQTT.Host = DEFAULT_HOST
		}
		if opts.MQTT.TLSTimeout == 0 {
			opts.MQTT.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second)
		}
	}
	// JetStream
	if opts.JetStreamMaxMemory == 0 && !opts.maxMemSet {
		opts.JetStreamMaxMemory = -1
	}
	if opts.JetStreamMaxStore == 0 && !opts.maxStoreSet {
		opts.JetStreamMaxStore = -1
	}
	if opts.SyncInterval == 0 && !opts.syncSet {
		opts.SyncInterval = defaultSyncInterval
	}
	if opts.JetStreamRequestQueueLimit <= 0 {
		opts.JetStreamRequestQueueLimit = JSDefaultRequestQueueLimit
	}
}

func getDefaultAuthTimeout(tls *tls.Config, tlsTimeout float64) float64 {
	var authTimeout float64
	if tls != nil {
		authTimeout = tlsTimeout + 1.0
	} else {
		authTimeout = float64(AUTH_TIMEOUT / time.Second)
	}
	return authTimeout
}

// ConfigureOptions accepts a flag set and augments it with NATS Server
// specific flags. On success, an options structure is returned configured
// based on the selected flags and/or configuration file.
// The command line options take precedence to the ones in the configuration file.
func ConfigureOptions(fs *flag.FlagSet, args []string, printVersion, printHelp, printTLSHelp func()) (*Options, error) {
	opts := &Options{}
	var (
		showVersion            bool
		showHelp               bool
		showTLSHelp            bool
		signal                 string
		configFile             string
		dbgAndTrace            bool
		trcAndVerboseTrc       bool
		dbgAndTrcAndVerboseTrc bool
		err                    error
	)

	fs.BoolVar(&showHelp, "h", false, "Show this message.")
	fs.BoolVar(&showHelp, "help", false, "Show this message.")
	fs.IntVar(&opts.Port, "port", 0, "Port to listen on.")
	fs.IntVar(&opts.Port, "p", 0, "Port to listen on.")
	fs.StringVar(&opts.ServerName, "n", _EMPTY_, "Server name.")
	fs.StringVar(&opts.ServerName, "name", _EMPTY_, "Server name.")
	fs.StringVar(&opts.ServerName, "server_name", _EMPTY_, "Server name.")
	fs.StringVar(&opts.Host, "addr", _EMPTY_, "Network host to listen on.")
	fs.StringVar(&opts.Host, "a", _EMPTY_, "Network host to listen on.")
	fs.StringVar(&opts.Host, "net", _EMPTY_, "Network host to listen on.")
	fs.StringVar(&opts.ClientAdvertise, "client_advertise", _EMPTY_, "Client URL to advertise to other servers.")
	fs.BoolVar(&opts.Debug, "D", false, "Enable Debug logging.")
	fs.BoolVar(&opts.Debug, "debug", false, "Enable Debug logging.")
	fs.BoolVar(&opts.Trace, "V", false, "Enable Trace logging.")
	fs.BoolVar(&trcAndVerboseTrc, "VV", false, "Enable Verbose Trace logging. (Traces system account as well)")
	fs.BoolVar(&opts.Trace, "trace", false, "Enable Trace logging.")
	fs.BoolVar(&dbgAndTrace, "DV", false, "Enable Debug and Trace logging.")
	fs.BoolVar(&dbgAndTrcAndVerboseTrc, "DVV", false, "Enable Debug and Verbose Trace logging. (Traces system account as well)")
	fs.BoolVar(&opts.Logtime, "T", true, "Timestamp log entries.")
	fs.BoolVar(&opts.Logtime, "logtime", true, "Timestamp log entries.")
	fs.BoolVar(&opts.LogtimeUTC, "logtime_utc", false, "Timestamps in UTC instead of local timezone.")
	fs.StringVar(&opts.Username, "user", _EMPTY_, "Username required for connection.")
	fs.StringVar(&opts.Password, "pass", _EMPTY_, "Password required for connection.")
	fs.StringVar(&opts.Authorization, "auth", _EMPTY_, "Authorization token required for connection.")
	fs.IntVar(&opts.HTTPPort, "m", 0, "HTTP Port for /varz, /connz endpoints.")
	fs.IntVar(&opts.HTTPPort, "http_port", 0, "HTTP Port for /varz, /connz endpoints.")
	fs.IntVar(&opts.HTTPSPort, "ms", 0, "HTTPS Port for /varz, /connz endpoints.")
	fs.IntVar(&opts.HTTPSPort, "https_port", 0, "HTTPS Port for /varz, /connz endpoints.")
	fs.StringVar(&configFile, "c", _EMPTY_, "Configuration file.")
	fs.StringVar(&configFile, "config", _EMPTY_, "Configuration file.")
	fs.BoolVar(&opts.CheckConfig, "t", false, "Check configuration and exit.")
	fs.StringVar(&signal, "sl", "", "Send signal to nats-server process (ldm, stop, quit, term, reopen, reload).")
	fs.StringVar(&signal, "signal", "", "Send signal to nats-server process (ldm, stop, quit, term, reopen, reload).")
	fs.StringVar(&opts.PidFile, "P", "", "File to store process pid.")
	fs.StringVar(&opts.PidFile, "pid", "", "File to store process pid.")
	fs.StringVar(&opts.PortsFileDir, "ports_file_dir", "", "Creates a ports file in the specified directory (<executable_name>_<pid>.ports).")
	fs.StringVar(&opts.LogFile, "l", "", "File to store logging output.")
	fs.StringVar(&opts.LogFile, "log", "", "File to store logging output.")
	fs.Int64Var(&opts.LogSizeLimit, "log_size_limit", 0, "Logfile size limit being auto-rotated")
	fs.BoolVar(&opts.Syslog, "s", false, "Enable syslog as log method.")
	fs.BoolVar(&opts.Syslog, "syslog", false, "Enable syslog as log method.")
	fs.StringVar(&opts.RemoteSyslog, "r", _EMPTY_, "Syslog server addr (udp://127.0.0.1:514).")
	fs.StringVar(&opts.RemoteSyslog, "remote_syslog", _EMPTY_, "Syslog server addr (udp://127.0.0.1:514).")
	fs.BoolVar(&showVersion, "version", false, "Print version information.")
	fs.BoolVar(&showVersion, "v", false, "Print version information.")
	fs.IntVar(&opts.ProfPort, "profile", 0, "Profiling HTTP port.")
	fs.StringVar(&opts.RoutesStr, "routes", _EMPTY_, "Routes to actively solicit a connection.")
	fs.StringVar(&opts.Cluster.ListenStr, "cluster", _EMPTY_, "Cluster url from which members can solicit routes.")
	fs.StringVar(&opts.Cluster.ListenStr, "cluster_listen", _EMPTY_, "Cluster url from which members can solicit routes.")
	fs.StringVar(&opts.Cluster.Advertise, "cluster_advertise", _EMPTY_, "Cluster URL to advertise to other servers.")
	fs.BoolVar(&opts.Cluster.NoAdvertise, "no_advertise", false, "Advertise known cluster IPs to clients.")
	fs.IntVar(&opts.Cluster.ConnectRetries, "connect_retries", 0, "For implicit routes, number of connect retries.")
	fs.StringVar(&opts.Cluster.Name, "cluster_name", _EMPTY_, "Cluster Name, if not set one will be dynamically generated.")
	fs.BoolVar(&showTLSHelp, "help_tls", false, "TLS help.")
	fs.BoolVar(&opts.TLS, "tls", false, "Enable TLS.")
	fs.BoolVar(&opts.TLSVerify, "tlsverify", false, "Enable TLS with client verification.")
	fs.StringVar(&opts.TLSCert, "tlscert", _EMPTY_, "Server certificate file.")
	fs.StringVar(&opts.TLSKey, "tlskey", _EMPTY_, "Private key for server certificate.")
	fs.StringVar(&opts.TLSCaCert, "tlscacert", _EMPTY_, "Client certificate CA for verification.")
	fs.IntVar(&opts.MaxTracedMsgLen, "max_traced_msg_len", 0, "Maximum printable length for traced messages. 0 for unlimited.")
	fs.BoolVar(&opts.JetStream, "js", false, "Enable JetStream.")
	fs.BoolVar(&opts.JetStream, "jetstream", false, "Enable JetStream.")
	fs.StringVar(&opts.StoreDir, "sd", _EMPTY_, "Storage directory.")
	fs.StringVar(&opts.StoreDir, "store_dir", _EMPTY_, "Storage directory.")

	// The flags definition above set "default" values to some of the options.
	// Calling Parse() here will override the default options with any value
	// specified from the command line. This is ok. We will then update the
	// options with the content of the configuration file (if present), and then,
	// call Parse() again to override the default+config with command line values.
	// Calling Parse() before processing config file is necessary since configFile
	// itself is a command line argument, and also Parse() is required in order
	// to know if user wants simply to show "help" or "version", etc...
	if err := fs.Parse(args); err != nil {
		return nil, err
	}

	if showVersion {
		printVersion()
		return nil, nil
	}

	if showHelp {
		printHelp()
		return nil, nil
	}

	if showTLSHelp {
		printTLSHelp()
		return nil, nil
	}

	// Process args looking for non-flag options,
	// 'version' and 'help' only for now
	showVersion, showHelp, err = ProcessCommandLineArgs(fs)
	if err != nil {
		return nil, err
	} else if showVersion {
		printVersion()
		return nil, nil
	} else if showHelp {
		printHelp()
		return nil, nil
	}

	// Snapshot flag options.
	FlagSnapshot = opts.Clone()

	// Keep track of the boolean flags that were explicitly set with their value.
	fs.Visit(func(f *flag.Flag) {
		switch f.Name {
		case "DVV":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", dbgAndTrcAndVerboseTrc)
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", dbgAndTrcAndVerboseTrc)
			trackExplicitVal(&FlagSnapshot.inCmdLine, "TraceVerbose", dbgAndTrcAndVerboseTrc)
		case "DV":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", dbgAndTrace)
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", dbgAndTrace)
		case "D":
			fallthrough
		case "debug":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", FlagSnapshot.Debug)
		case "VV":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", trcAndVerboseTrc)
			trackExplicitVal(&FlagSnapshot.inCmdLine, "TraceVerbose", trcAndVerboseTrc)
		case "V":
			fallthrough
		case "trace":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", FlagSnapshot.Trace)
		case "T":
			fallthrough
		case "logtime":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Logtime", FlagSnapshot.Logtime)
		case "s":
			fallthrough
		case "syslog":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Syslog", FlagSnapshot.Syslog)
		case "no_advertise":
			trackExplicitVal(&FlagSnapshot.inCmdLine, "Cluster.NoAdvertise", FlagSnapshot.Cluster.NoAdvertise)
		}
	})

	// Process signal control.
	if signal != _EMPTY_ {
		if err := processSignal(signal); err != nil {
			return nil, err
		}
	}

	// Parse config if given
	if configFile != _EMPTY_ {
		// This will update the options with values from the config file.
		err := opts.ProcessConfigFile(configFile)
		if err != nil {
			if opts.CheckConfig {
				return nil, err
			}
			if cerr, ok := err.(*processConfigErr); !ok || len(cerr.Errors()) != 0 {
				return nil, err
			}
			// If we get here we only have warnings and can still continue
			fmt.Fprint(os.Stderr, err)
		} else if opts.CheckConfig {
			// Report configuration file syntax test was successful and exit.
			return opts, nil
		}

		// Call this again to override config file options with options from command line.
		// Note: We don't need to check error here since if there was an error, it would
		// have been caught the first time this function was called (after setting up the
		// flags).
		fs.Parse(args)
	} else if opts.CheckConfig {
		return nil, fmt.Errorf("must specify [-c, --config] option to check configuration file syntax")
	}

	// Special handling of some flags
	var (
		flagErr     error
		tlsDisabled bool
		tlsOverride bool
	)
	fs.Visit(func(f *flag.Flag) {
		// short-circuit if an error was encountered
		if flagErr != nil {
			return
		}
		if strings.HasPrefix(f.Name, "tls") {
			if f.Name == "tls" {
				if !opts.TLS {
					// User has specified "-tls=false", we need to disable TLS
					opts.TLSConfig = nil
					tlsDisabled = true
					tlsOverride = false
					return
				}
				tlsOverride = true
			} else if !tlsDisabled {
				tlsOverride = true
			}
		} else {
			switch f.Name {
			case "VV":
				opts.Trace, opts.TraceVerbose = trcAndVerboseTrc, trcAndVerboseTrc
			case "DVV":
				opts.Trace, opts.Debug, opts.TraceVerbose = dbgAndTrcAndVerboseTrc, dbgAndTrcAndVerboseTrc, dbgAndTrcAndVerboseTrc
			case "DV":
				// Check value to support -DV=false
				opts.Trace, opts.Debug = dbgAndTrace, dbgAndTrace
			case "cluster", "cluster_listen":
				// Override cluster config if explicitly set via flags.
				flagErr = overrideCluster(opts)
			case "routes":
				// Keep in mind that the flag has updated opts.RoutesStr at this point.
				if opts.RoutesStr == _EMPTY_ {
					// Set routes array to nil since routes string is empty
					opts.Routes = nil
					return
				}
				routeUrls := RoutesFromStr(opts.RoutesStr)
				opts.Routes = routeUrls
			}
		}
	})
	if flagErr != nil {
		return nil, flagErr
	}

	// This will be true if some of the `-tls` params have been set and
	// `-tls=false` has not been set.
	if tlsOverride {
		if err := overrideTLS(opts); err != nil {
			return nil, err
		}
	}

	// If we don't have cluster defined in the configuration
	// file and no cluster listen string override, but we do
	// have a routes override, we need to report misconfiguration.
	if opts.RoutesStr != _EMPTY_ && opts.Cluster.ListenStr == _EMPTY_ && opts.Cluster.Host == _EMPTY_ && opts.Cluster.Port == 0 {
		return nil, errors.New("solicited routes require cluster capabilities, e.g. --cluster")
	}

	return opts, nil
}

func normalizeBasePath(p string) string {
	if len(p) == 0 {
		return "/"
	}
	// add leading slash
	if p[0] != '/' {
		p = "/" + p
	}
	return path.Clean(p)
}

// overrideTLS is called when at least "-tls=true" has been set.
func overrideTLS(opts *Options) error {
	if opts.TLSCert == _EMPTY_ {
		return errors.New("TLS Server certificate must be present and valid")
	}
	if opts.TLSKey == _EMPTY_ {
		return errors.New("TLS Server private key must be present and valid")
	}

	tc := TLSConfigOpts{}
	tc.CertFile = opts.TLSCert
	tc.KeyFile = opts.TLSKey
	tc.CaFile = opts.TLSCaCert
	tc.Verify = opts.TLSVerify
	tc.Ciphers = defaultCipherSuites()

	var err error
	opts.TLSConfig, err = GenTLSConfig(&tc)
	return err
}

// overrideCluster updates Options.Cluster if that flag "cluster" (or "cluster_listen")
// has explicitly be set in the command line. If it is set to empty string, it will
// clear the Cluster options.
func overrideCluster(opts *Options) error {
	if opts.Cluster.ListenStr == _EMPTY_ {
		// This one is enough to disable clustering.
		opts.Cluster.Port = 0
		return nil
	}
	// -1 will fail url.Parse, so if we have -1, change it to
	// 0, and then after parse, replace the port with -1 so we get
	// automatic port allocation
	wantsRandom := false
	if strings.HasSuffix(opts.Cluster.ListenStr, ":-1") {
		wantsRandom = true
		cls := fmt.Sprintf("%s:0", opts.Cluster.ListenStr[0:len(opts.Cluster.ListenStr)-3])
		opts.Cluster.ListenStr = cls
	}
	clusterURL, err := url.Parse(opts.Cluster.ListenStr)
	if err != nil {
		return err
	}
	h, p, err := net.SplitHostPort(clusterURL.Host)
	if err != nil {
		return err
	}
	if wantsRandom {
		p = "-1"
	}
	opts.Cluster.Host = h
	_, err = fmt.Sscan(p, &opts.Cluster.Port)
	if err != nil {
		return err
	}

	if clusterURL.User != nil {
		pass, hasPassword := clusterURL.User.Password()
		if !hasPassword {
			return errors.New("expected cluster password to be set")
		}
		opts.Cluster.Password = pass

		user := clusterURL.User.Username()
		opts.Cluster.Username = user
	} else {
		// Since we override from flag and there is no user/pwd, make
		// sure we clear what we may have gotten from config file.
		opts.Cluster.Username = _EMPTY_
		opts.Cluster.Password = _EMPTY_
	}

	return nil
}

func processSignal(signal string) error {
	var (
		pid           string
		commandAndPid = strings.Split(signal, "=")
	)
	if l := len(commandAndPid); l == 2 {
		pid = maybeReadPidFile(commandAndPid[1])
	} else if l > 2 {
		return fmt.Errorf("invalid signal parameters: %v", commandAndPid[2:])
	}
	if err := ProcessSignal(Command(commandAndPid[0]), pid); err != nil {
		return err
	}
	os.Exit(0)
	return nil
}

// maybeReadPidFile returns a PID or Windows service name obtained via the following method:
// 1. Try to open a file with path "pidStr" (absolute or relative).
// 2. If such a file exists and can be read, return its contents.
// 3. Otherwise, return the original "pidStr" string.
func maybeReadPidFile(pidStr string) string {
	if b, err := os.ReadFile(pidStr); err == nil {
		return string(b)
	}
	return pidStr
}

func homeDir() (string, error) {
	if runtime.GOOS == "windows" {
		homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")
		userProfile := os.Getenv("USERPROFILE")

		home := filepath.Join(homeDrive, homePath)
		if homeDrive == _EMPTY_ || homePath == _EMPTY_ {
			if userProfile == _EMPTY_ {
				return _EMPTY_, errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%")
			}
			home = userProfile
		}

		return home, nil
	}

	home := os.Getenv("HOME")
	if home == _EMPTY_ {
		return _EMPTY_, errors.New("failed to get home dir, require $HOME")
	}
	return home, nil
}

func expandPath(p string) (string, error) {
	p = os.ExpandEnv(p)

	if !strings.HasPrefix(p, "~") {
		return p, nil
	}

	home, err := homeDir()
	if err != nil {
		return _EMPTY_, err
	}

	return filepath.Join(home, p[1:]), nil
}