File: ddclient.in

package info (click to toggle)
ddclient 3.11.2-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,284 kB
  • sloc: perl: 14,597; sh: 916; makefile: 146; xml: 55
file content (7891 lines) | stat: -rwxr-xr-x 318,507 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
#!/usr/bin/perl
######################################################################
#
# DDCLIENT - a Perl client for updating DynDNS information
#
# Original Author: Paul Burry (paul+ddclient@burry.ca)
# Current maintainers:
#   Reuben Thomas <rrt@sc3d.org>
#   Lenard Heß <lenard@rrhess.de>
#
# website: https://github.com/ddclient/ddclient
#
######################################################################
package ddclient;
require v5.10.1;
use strict;
use warnings;
use File::Basename;
use File::Path qw(make_path);
use File::Temp;
use Getopt::Long;
use Sys::Hostname;

use version 0.77; our $VERSION = version->declare('3.11.2');
my $version = $VERSION->stringify();
my $programd = $0;
$programd =~ s%^.*/%%;
my $program = $programd;
$program =~ s/d$//;
my $now = time;
my $hostname = hostname();

# subst_var(subst, default) returns subst unless it looks like @foo@ in which case it returns
# default. The @foo@ strings are expected to be replaced by make; this function makes it possible
# to run this file as a Perl script before those substitutions are made.
sub subst_var {
    my ($subst, $default) = @_;
    return $default if $subst =~ qr'^@\w+@$';
    return $subst;
}

my $etc = subst_var('@sysconfdir@', '/etc/ddclient');
my $cachedir = subst_var('@localstatedir@', '/var') . '/cache/ddclient';
my $savedir = '/tmp';
if ($program =~ /test/i) {
    $etc = '.';
    $cachedir = '.';
    $savedir = 'URL';
}

my $msgs      = '';
my $last_msgs = '';

## If run as *d (e.g., ddclientd) then daemonize by default (but allow
## flags and options to override).
my $daemon_default = ($programd =~ /d$/) ? interval('5m') : 0;

use vars qw($file $lineno);
local $file   = '';
local $lineno = '';

$ENV{'PATH'} = (exists($ENV{PATH}) ? "$ENV{PATH}:" : "") . "/sbin:/usr/sbin:/bin:/usr/bin:/etc:/usr/lib:";

our %globals;
my ($result, %config, %cache);
my $saved_cache;
my %saved_opt;
my $daemon;
# Control how many times warning message logged for invalid IP addresses
my (%warned_ip, %warned_ipv4, %warned_ipv6);
my $inv_ip_warn_count = opt('max-warn') // 1;

sub T_ANY    { 'any' }
sub T_STRING { 'string' }
sub T_EMAIL  { 'e-mail address' }
sub T_NUMBER { 'number' }
sub T_DELAY  { 'time delay (ie. 1d, 1hour, 1m)' }
sub T_LOGIN  { 'login' }
sub T_PASSWD { 'password' }
sub T_BOOL   { 'boolean value' }
sub T_FQDN   { 'fully qualified host name' }
sub T_OFQDN  { 'optional fully qualified host name' }
sub T_FILE   { 'file name' }
sub T_FQDNP  { 'fully qualified host name and optional port number' }
sub T_PROTO  { 'protocol' }
sub T_USE    { 'ip strategy' }
sub T_USEV4  { 'ipv4 strategy' }
sub T_USEV6  { 'ipv6 strategy' }
sub T_IF     { 'interface' }
sub T_PROG   { 'program name' }
sub T_IP     { 'ip' }
sub T_IPV4   { 'ipv4' }
sub T_IPV6   { 'ipv6' }
sub T_POSTS  { 'postscript' }

## strategies for obtaining an ip address.
my %builtinweb = (
    'dyndns' => {'url' => 'http://checkip.dyndns.org/', 'skip' => 'Current IP Address:'},
    'freedns' => {'url' => 'https://freedns.afraid.org/dynamic/check.php'},
    'googledomains' => {'url' => 'https://domains.google.com/checkip'},
    'he' => {'url' => 'https://checkip.dns.he.net/'},
    'ip4only.me' => {'url' => 'https://ip4only.me/api/'},
    'ip6only.me' => {'url' => 'https://ip6only.me/api/'},
    'ipify-ipv4' => {'url' => 'https://api.ipify.org/'},
    'ipify-ipv6' => {'url' => 'https://api6.ipify.org/'},
    'loopia' => {'url' => 'https://dns.loopia.se/checkip/checkip.php', 'skip' => 'Current IP Address:'},
    'myonlineportal' => {'url' => 'https://myonlineportal.net/checkip'},
    'noip-ipv4' => {'url' => 'http://ip1.dynupdate.no-ip.com/'},
    'noip-ipv6' => {'url' => 'http://ip1.dynupdate6.no-ip.com/'},
    'nsupdate.info-ipv4' => {'url' => 'https://ipv4.nsupdate.info/myip'},
    'nsupdate.info-ipv6' => {'url' => 'https://ipv6.nsupdate.info/myip'},
    'zoneedit' => {'url' => 'https://dynamic.zoneedit.com/checkip.html'},
);
my %builtinfw = (
    '2wire' => {
        'name' => '2Wire 1701HG Gateway',
        'url'  => '/xslt?PAGE=B01',
        'skip' => 'Internet Address:',
    },
    '3com-3c886a' => {
        'name' => '3com 3c886a 56k Lan Modem',
        'url'  => '/stat3.htm',
        'skip' => 'IP address in use',
    },
    '3com-oc-remote812' => {
        'name' => '3com OfficeConnect Remote 812',
        'url'  => '/callEvent',
        'skip' => '.*LOCAL',
    },
    'alcatel-510' => {
        'name' => 'Alcatel Speed Touch 510',
        'url'  => '/cgi/ip/',
        'skip' => 'ppp',
    },
    'alcatel-530' => {
        'name' => 'Alcatel/Thomson SpeedTouch 530',
        'url'  => '/cgi/status/',
        'skip' => 'IP Address',
    },
    'alcatel-stp' => {
        'name' => 'Alcatel Speed Touch Pro',
        'url'  => '/cgi/router/',
        'skip' => 'Brt',
    },
    'allnet-1298' => {
        'name' => 'Allnet 1298',
        'url'  => '/cgi/router/',
        'skip' => 'WAN',
    },
    'cayman-3220h' => {
        'name' => 'Cayman 3220-H DSL',
        'url'  => '/shell/show+ip+interfaces',
        'skip' => '.*inet',
    },
    'dlink-524' => {
        'name' => 'D-Link DI-524',
        'url'  => '/st_device.html',
        'skip' => 'WAN.*?Addres',
    },
    'dlink-604' => {
        'name' => 'D-Link DI-604',
        'url'  => '/st_devic.html',
        'skip' => 'WAN.*?IP.*Address',
    },
    'dlink-614' => {
        'name' => 'D-Link DI-614+',
        'url'  => '/st_devic.html',
        'skip' => 'WAN',
    },
    'e-tech' => {
        'name' => 'E-tech Router',
        'url'  => '/Status.htm',
        'skip' => 'Public IP Address',
    },
    'elsa-lancom-dsl10' => {
        'name' => 'ELSA LanCom DSL/10 DSL FW',
        'url'  => '/config/1/6/8/3/',
        'skip' => 'IP.Address',
    },
    'elsa-lancom-dsl10-ch01' => {
        'name' => 'ELSA LanCom DSL/10 DSL FW (isdn ch01)',
        'url'  => '/config/1/6/8/3/',
        'skip' => 'IP.Address.*?CH01',
    },
    'elsa-lancom-dsl10-ch02' => {
        'name' => 'ELSA LanCom DSL/10 DSL FW (isdn ch01)',
        'url'  => '/config/1/6/8/3/',
        'skip' => 'IP.Address.*?CH02',
    },
    'linksys' => {
        'name' => 'Linksys FW',
        'url'  => '/Status.htm',
        'skip' => 'WAN.*?Address',
    },
    'linksys-rv042-wan1' => {
        'name' => 'Linksys RV042 Dual Homed Router WAN Port 2',
        'url'  => '/home.htm',
        'skip' => 'WAN1 IP',
    },
    'linksys-rv042-wan2' => {
        'name' => 'Linksys RV042 Dual Homed Router WAN Port 2',
        'url'  => '/home.htm',
        'skip' => 'WAN2 IP',
    },
    'linksys-ver2' => {
        'name' => 'Linksys FW version 2',
        'url'  => '/RouterStatus.htm',
        'skip' => 'WAN.*?Address',
    },
    'linksys-ver3' => {
        'name' => 'Linksys FW version 3',
        'url'  => '/Status_Router.htm',
        'skip' => 'WAN.*?Address',
    },
    'linksys-wcg200' => {
        'name' => 'Linksys WCG200 FW',
        'url'  => '/RgStatus.asp',
        'skip' => 'WAN.IP.*?Address',
    },
    'linksys-wrt854g' => {
        'name' => 'Linksys WRT854G FW',
        'url'  => '/Status_Router.asp',
        'skip' => 'IP Address:',
    },
    'maxgate-ugate3x00' => {
        'name' => 'MaxGate UGATE-3x00 FW',
        'url'  => '/Status.htm',
        'skip' => 'WAN.*?IP Address',
    },
    'netcomm-nb3' => {
        'name' => 'NetComm NB3',
        'url'  => '/MainPage?id=6',
        'skip' => 'ppp-0',
    },
    'netgear-dg834g' => {
        'name' => 'netgear-dg834g',
        'url'  => '/setup.cgi?next_file=s_status.htm&todo=cfg_init',
        'skip' => '',
    },
    'netgear-rp614' => {
        'name' => 'Netgear RP614 FW',
        'url'  => '/sysstatus.html',
        'skip' => 'IP Address',
    },
    'netgear-rt3xx' => {
        'name' => 'Netgear FW',
        'url'  => '/mtenSysStatus.html',
        'skip' => 'IP Address',
    },
    'netgear-wgt624' => {
        'name' => 'Netgear WGT624',
        'url'  => '/RST_st_dhcp.htm',
        'skip' => 'IP Address</B></td><TD NOWRAP width="50%">',
    },
    'netgear-wpn824' => {
        'name' => 'Netgear WPN824 FW',
        'url'  => '/RST_status.htm',
        'skip' => 'IP Address',
    },
    'netopia-r910' => {
        'name' => 'Netopia R910 FW',
        'url'  => '/WanEvtLog',
        'skip' => 'local:',
    },
    'olitec-SX200' => {
        'name' => 'olitec-SX200',
        'url'  => '/doc/wan.htm',
        'skip' => 'st_wan_ip[0] = "',
    },
    'rtp300' => {
        'name' => 'Linksys RTP300',
        'url'  => '/cgi-bin/webcm?getpage=%2Fusr%2Fwww_safe%2Fhtml%2Fstatus%2FRouter.html',
        'skip' => 'Internet.*?IP Address',
    },
    'siemens-ss4200' => {
        'name' => 'Siemens SpeedStream 4200',
        'url'  => '/summary.htm',
        'skip' => '',
    },
    'sitecom-dc202' => {
        'name' => 'Sitecom DC-202 FW',
        'url'  => '/status.htm',
        'skip' => 'Internet IP Address',
    },
    'smc-barricade' => {
        'name' => 'SMC Barricade FW',
        'url'  => '/status.htm',
        'skip' => 'IP Address',
    },
    'smc-barricade-7004vbr' => {
        'name' => 'SMC Barricade FW (7004VBR model config)',
        'url'  => '/status_main.stm',
        'skip' => 'var wan_ip=',
    },
    'smc-barricade-7401bra' => {
        'name' => 'SMC Barricade 7401BRA FW',
        'url'  => '/admin/wan1.htm',
        'skip' => 'IP Address',
    },
    'smc-barricade-alt' => {
        'name' => 'SMC Barricade FW (alternate config)',
        'url'  => '/status.HTM',
        'skip' => 'WAN IP',
    },
    'sohoware-nbg800' => {
        'name' => 'SOHOWare BroadGuard NBG800',
        'url'  => '/status.htm',
        'skip' => 'Internet IP',
    },
    'sveasoft' => {
        'name' => 'Sveasoft WRT54G/WRT54GS',
        'url'  => '/Status_Router.asp',
        'skip' => 'var wan_ip',
    },
    'thomson-st536v6' => {
        'name' => 'Thomson SpeedTouch 536v6',
        'url'  => '/cgi/b/is/',
        'skip' => 'IP Address',
    },
    'thomson-tg782' => {
        'name' => 'Thomson/Technicolor TG782',
        'url'  => '/cgi/b/is/',
        'skip' => 'IP Address',
    },
    'vigor-2200usb' => {
        'name' => 'Vigor 2200 USB',
        'url'  => '/doc/online.sht',
        'skip' => 'PPPoA',
    },
    'watchguard-edge-x' => {
        'name' => 'Watchguard Edge X FW',
        'url'  => '/netstat.htm',
        'skip' => 'inet addr:',
    },
    'watchguard-soho' => {
        'name' => 'Watchguard SOHO FW',
        'url'  => '/pubnet.htm',
        'skip' => 'NAME=IPAddress VALUE=',
    },
    'westell-6100' => {
        'name' => 'Westell C90-610015-06 DSL Router',
        'url'  => '/advstat.htm',
        'skip' => 'IP.+?Address',
    },
    'xsense-aero' => {
        'name' => 'Xsense Aero',
        'url'  => '/A_SysInfo.htm',
        'skip' => 'WAN.*?IP Address',
    },
);

my %ip_strategies = (
    'no'        => ": deprecated, see 'usev4' and 'usev6'",
    'ip'        => ": deprecated, see 'usev4' and 'usev6'",
    'web'       => ": deprecated, see 'usev4' and 'usev6'",
    'fw'        => ": deprecated, see 'usev4' and 'usev6'",
    'if'        => ": deprecated, see 'usev4' and 'usev6'",
    'cmd'       => ": deprecated, see 'usev4' and 'usev6'",
    'cisco'     => ": deprecated, see 'usev4' and 'usev6'",
    'cisco-asa' => ": deprecated, see 'usev4' and 'usev6'",
    map({ $_ => sprintf(": Built-in firewall %s deprecated, see 'usev4' and 'usev6'",
                        $builtinfw{$_}->{'name'}) }
        keys(%builtinfw)),
);

sub ip_strategies_usage {
    return map({ sprintf("    -use=%-22s %s.", $_, $ip_strategies{$_}) }
               ('ip', 'web', 'if', 'cmd', 'fw', sort('cisco', 'cisco-asa', keys(%builtinfw))));
}

my %ipv4_strategies = (
    'disabled'    => ": do not obtain an IPv4 address for this host",
    'ipv4'        => ": obtain IPv4 from -ipv4 {address}",
    'webv4'       => ": obtain IPv4 from an IP discovery page on the web",
    'ifv4'        => ": obtain IPv4 from the -ifv4 {interface}",
    'cmdv4'       => ": obtain IPv4 from the -cmdv4 {external-command}",
    'fwv4'        => ": obtain IPv4 from the firewall specified by -fwv4 {type|address}",
    'ciscov4'     => ": obtain IPv4 from Cisco FW at the -fwv4 {address}",
    'cisco-asav4' => ": obtain IPv4 from Cisco ASA at the -fwv4 {address}",
    map { $_ => sprintf ": obtain IPv4 from %s at the -fwv4 {address}", $builtinfw{$_}->{'name'} } keys %builtinfw,
);
sub ipv4_strategies_usage {
    return map { sprintf("    -usev4=%-22s %s.", $_, $ipv4_strategies{$_}) } sort keys %ipv4_strategies;
}

my %ipv6_strategies = (
    'no'          => ": deprecated, use 'disabled'",
    'disabled'    => ": do not obtain an IPv6 address for this host",
    'ip'          => ": deprecated, use 'ipv6'",
    'ipv6'        => ": obtain IPv6 from -ipv6 {address}",
    'web'         => ": deprecated, use 'webv6'",
    'webv6'       => ": obtain IPv6 from an IP discovery page on the web",
    'if'          => ": deprecated, use 'ifv6'",
    'ifv6'        => ": obtain IPv6 from the -if {interface}",
    'cmd'         => ": deprecated, use 'cmdv6'",
    'cmdv6'       => ": obtain IPv6 from the -cmdv6 {external-command}",
    'fwv6'        => ": obtain IPv6 from the firewall specified by -fwv6 {type|address}",
    'ciscov6'     => ": obtain IPv6 from Cisco FW at the -fwv6 {address}",
    'cisco-asav6' => ": obtain IPv6 from Cisco ASA at the -fwv6 {address}",
    map { $_ => sprintf ": obtain IPv6 from %s at the -fwv6 {address}", $builtinfw{$_}->{'name'} } keys %builtinfw,
);
sub ipv6_strategies_usage {
    return map { sprintf("    -usev6=%-22s %s.", $_, $ipv6_strategies{$_}) } sort keys %ipv6_strategies;
}

sub setv {
    return {
        'type'     => shift,
        'required' => shift,
        'cache'    => shift,
        'default'  => shift,
        'minimum'  => shift,
    };
}
my %variables = (
    'global-defaults' => {
        'daemon'              => setv(T_DELAY, 0, 0, $daemon_default,      interval('60s')),
        'foreground'          => setv(T_BOOL,  0, 0, 0,                    undef),
        'file'                => setv(T_FILE,  0, 0, "$etc/$program.conf", undef),
        'cache'               => setv(T_FILE,  0, 0, "$cachedir/$program.cache", undef),
        'pid'                 => setv(T_FILE,  0, 0, "",                   undef),
        'proxy'               => setv(T_FQDNP, 0, 0, undef,                undef),
        'protocol'            => setv(T_PROTO, 0, 0, 'dyndns2',            undef),

        'use'                 => setv(T_USE,   0, 0, 'ip',                 undef),
        'usev4'               => setv(T_USEV4, 0, 0, 'disabled',           undef),
        'usev6'               => setv(T_USEV6, 0, 0, 'disabled',           undef),
        'ip'                  => setv(T_IP,    0, 0, undef,                undef),
        'ipv4'                => setv(T_IPV4,  0, 0, undef,                undef),
        'ipv6'                => setv(T_IPV6,  0, 0, undef,                undef),
        'if'                  => setv(T_IF,    0, 0, 'ppp0',               undef),
        'ifv4'                => setv(T_IF,    0, 0, 'default',            undef),
        'ifv6'                => setv(T_IF,    0, 0, 'default',            undef),
        'web'                 => setv(T_STRING,0, 0, 'dyndns',             undef),
        'web-skip'            => setv(T_STRING,1, 0, '',                   undef),
        'webv4'               => setv(T_STRING,0, 0, 'googledomains',      undef),
        'webv4-skip'          => setv(T_STRING,1, 0, '',                   undef),
        'webv6'               => setv(T_STRING,0, 0, 'googledomains',      undef),
        'webv6-skip'          => setv(T_STRING,1, 0, '',                   undef),
        'fw'                  => setv(T_ANY,   0, 0, '',                   undef),
        'fw-skip'             => setv(T_STRING,1, 0, '',                   undef),
        'fwv4'                => setv(T_ANY,   0, 0, '',                   undef),
        'fwv4-skip'           => setv(T_STRING,1, 0, '',                   undef),
        'fwv6'                => setv(T_ANY,   0, 0, '',                   undef),
        'fwv6-skip'           => setv(T_STRING,1, 0, '',                   undef),
        'fw-login'            => setv(T_LOGIN, 1, 0, '',                   undef),
        'fw-password'         => setv(T_PASSWD,1, 0, '',                   undef),
        'cmd'                 => setv(T_PROG,  0, 0, '',                   undef),
        'cmd-skip'            => setv(T_STRING,1, 0, '',                   undef),
        'cmdv4'               => setv(T_PROG,  0, 0, '',                   undef),
        'cmdv6'               => setv(T_PROG,  0, 0, '',                   undef),

        'timeout'             => setv(T_DELAY, 0, 0, interval('120s'),     interval('120s')),
        'retry'               => setv(T_BOOL,  0, 0, 0,                    undef),
        'force'               => setv(T_BOOL,  0, 0, 0,                    undef),
        'ssl'                 => setv(T_BOOL,  0, 0, 0,                    undef),
        'syslog'              => setv(T_BOOL,  0, 0, 0,                    undef),
        'facility'            => setv(T_STRING,0, 0, 'daemon',             undef),
        'priority'            => setv(T_STRING,0, 0, 'notice',             undef),
        'mail'                => setv(T_EMAIL, 0, 0, '',                   undef),
        'mail-failure'        => setv(T_EMAIL, 0, 0, '',                   undef),
        'max-warn'            => setv(T_NUMBER,0, 0, 1,                    undef),

        'exec'                => setv(T_BOOL,  0, 0, 1,                    undef),
        'debug'               => setv(T_BOOL,  0, 0, 0,                    undef),
        'verbose'             => setv(T_BOOL,  0, 0, 0,                    undef),
        'quiet'               => setv(T_BOOL,  0, 0, 0,                    undef),
        'help'                => setv(T_BOOL,  0, 0, 0,                    undef),
        'test'                => setv(T_BOOL,  0, 0, 0,                    undef),
        'geturl'              => setv(T_STRING,0, 0, '',                   undef),

        'postscript'          => setv(T_POSTS, 0, 0, '',                   undef),
        'ssl_ca_dir'          => setv(T_FILE,  0, 0, undef,                undef),
        'ssl_ca_file'         => setv(T_FILE,  0, 0, undef,                undef),
    },
    'service-common-defaults' => {
        'server'              => setv(T_FQDNP, 1, 0, 'members.dyndns.org', undef),
        'login'               => setv(T_LOGIN, 1, 0, '',                   undef),
        'password'            => setv(T_PASSWD,1, 0, '',                   undef),
        'host'                => setv(T_STRING,1, 1, '',                   undef),

        'use'                 => setv(T_USE,   0, 0, 'ip',                 undef),
        'usev4'               => setv(T_USEV4, 0, 0, 'disabled',           undef),
        'usev6'               => setv(T_USEV6, 0, 0, 'disabled',           undef),
        'if'                  => setv(T_IF,    0, 0, 'ppp0',               undef),
        'ifv4'                => setv(T_IF,    0, 0, 'default',            undef),
        'ifv6'                => setv(T_IF,    0, 0, 'default',            undef),
        'web'                 => setv(T_STRING,0, 0, 'dyndns',             undef),
        'web-skip'            => setv(T_STRING,0, 0, '',                   undef),
        'web-ssl-validate'    => setv(T_BOOL,  0, 0, 1,                    undef),
        'webv4'               => setv(T_STRING,0, 0, 'googledomains',      undef),
        'webv4-skip'          => setv(T_STRING,1, 0, '',                   undef),
        'webv6'               => setv(T_STRING,0, 0, 'googledomains',      undef),
        'webv6-skip'          => setv(T_STRING,1, 0, '',                   undef),
        'fw'                  => setv(T_ANY,   0, 0, '',                   undef),
        'fw-skip'             => setv(T_STRING,0, 0, '',                   undef),
        'fw-login'            => setv(T_LOGIN, 0, 0, '',                   undef),
        'fw-password'         => setv(T_PASSWD,0, 0, '',                   undef),
        'fw-ssl-validate'     => setv(T_BOOL,  0, 0, 1,                    undef),
        'fwv4'                => setv(T_ANY,   0, 0, '',                   undef),
        'fwv4-skip'           => setv(T_STRING,1, 0, '',                   undef),
        'fwv6'                => setv(T_ANY,   0, 0, '',                   undef),
        'fwv6-skip'           => setv(T_STRING,1, 0, '',                   undef),
        'cmd'                 => setv(T_PROG,  0, 0, '',                   undef),
        'cmd-skip'            => setv(T_STRING,0, 0, '',                   undef),
        'cmdv4'               => setv(T_PROG,  0, 0, '',                   undef),
        'cmdv6'               => setv(T_PROG,  0, 0, '',                   undef),
        
        'ip'                  => setv(T_IP,    0, 1, undef,                undef),  #TODO remove from cache?
        'ipv4'                => setv(T_IPV4,  0, 1, undef,                undef),
        'ipv6'                => setv(T_IPV6,  0, 1, undef,                undef),
        'wtime'               => setv(T_DELAY, 0, 1, 0,                    interval('30s')),
        'mtime'               => setv(T_NUMBER,0, 1, 0,                    undef),
        'atime'               => setv(T_NUMBER,0, 1, 0,                    undef),
        'status'              => setv(T_ANY,   0, 1, '',                   undef),  #TODO remove from cache?
        'status-ipv4'         => setv(T_ANY,   0, 1, '',                   undef),
        'status-ipv6'         => setv(T_ANY,   0, 1, '',                   undef),
        'min-interval'        => setv(T_DELAY, 0, 0, interval('30s'),      0),
        'max-interval'        => setv(T_DELAY, 0, 0, interval('30d'),      0),
        'min-error-interval'  => setv(T_DELAY, 0, 0, interval('5m'),       0),

        'warned-min-interval'       => setv(T_ANY, 0, 1, 0,                undef),
        'warned-min-error-interval' => setv(T_ANY, 0, 1, 0,                undef),
    },
    'dyndns-common-defaults' => {
        'backupmx'            => setv(T_BOOL,  0, 1, 0,                    undef),
        'mx'                  => setv(T_OFQDN, 0, 1, '',                   undef),
        'static'              => setv(T_BOOL,  0, 1, 0,                    undef),
        'wildcard'            => setv(T_BOOL,  0, 1, 0,                    undef),
    },
    'keysystems-common-defaults' => {
        'server'              => setv(T_FQDNP, 1, 0, 'dynamicdns.key-systems.net', undef),
        'login'               => setv(T_LOGIN, 0, 0, 0, 'unused',      undef),
    },
    'dnsexit2-common-defaults'       => {
        'ssl'         => setv(T_BOOL,   0, 0, 1, undef),
        'server'      => setv(T_FQDNP,  1, 0, 'api.dnsexit.com', undef),
        'path'        => setv(T_STRING, 0, 0, '/dns/', undef),
        'ttl'         => setv(T_NUMBER, 1, 0, 5, 0),
        'zone'        => setv(T_STRING, 0, 0, undef, undef)
    },
    'regfishde-common-defaults' => {
        'server'      => setv(T_FQDNP, 1, 0, 'dyndns.regfish.de', undef),
        'login'       => setv(T_LOGIN, 0, 0, 0, 'unused', undef),
    },
);
my %services = (
    '1984' => {
        'updateable' => undef,
        'update' => \&nic_1984_update,
        'examples' => \&nic_1984_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'login'  => setv(T_LOGIN, 0, 0, 'unused',      undef),
            'server' => setv(T_FQDNP, 1, 0, 'api.1984.is', undef),
        },
    },
    'changeip' => {
        'updateable' => undef,
        'update'     => \&nic_changeip_update,
        'examples'   => \&nic_changeip_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY, 0, 0, 0,                  interval('5m')),
            'server'       => setv(T_FQDNP, 1, 0, 'nic.changeip.com', undef),
        },
    },
    'cloudflare' => {
        'updateable' => undef,
        'update'     => \&nic_cloudflare_update,
        'examples'   => \&nic_cloudflare_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'backupmx'     => setv(T_BOOL,   0, 1, 0,                              undef),
            'login'        => setv(T_LOGIN,  0, 0, 'token',                        undef),
            'min-interval' => setv(T_DELAY,  0, 0, interval('5m'),                 0),
            'mx'           => setv(T_OFQDN,  0, 1, '',                             undef),
            'server'       => setv(T_FQDNP,  1, 0, 'api.cloudflare.com/client/v4', undef),
            'static'       => setv(T_BOOL,   0, 1, 0,                              undef),
            'ttl'          => setv(T_NUMBER, 1, 0, 1,                              undef),
            'wildcard'     => setv(T_BOOL,   0, 1, 0,                              undef),
            'zone'         => setv(T_FQDN,   1, 0, '',                             undef),
        },
    },
    'cloudns' => {
        'updateable' => undef,
        'update' => \&nic_cloudns_update,
        'examples' => \&nic_cloudns_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'dynurl' => setv(T_STRING, 1, 0, undef, undef),
            # nic_updateable() assumes that every service uses a username and password but that is
            # not true for CloudNS. Silence warnings by redefining the username and password
            # variables as non-required with a non-empty default.
            'login'    => setv(T_STRING, 0, 0, 'unused', undef),
            'password' => setv(T_STRING, 0, 0, 'unused', undef),
        },
    },
    'digitalocean' => {
        'updateable' => undef,
        'update' => \&nic_digitalocean_update,
        'examples' => \&nic_digitalocean_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'server' => setv(T_FQDNP, 1, 0, 'api.digitalocean.com', undef),
            'zone'   => setv(T_FQDN,  1, 0, '',                     undef),
            'login'  => setv(T_LOGIN, 0, 0, 'unused',               undef),
        },
    },
    'dinahosting' => {
        'updateable' => undef,
        'update'     => \&nic_dinahosting_update,
        'examples'   => \&nic_dinahosting_examples,
        'variables'  => {
            %{$variables{'service-common-defaults'}},
            'min-error-interval' => setv(T_DELAY,  0, 0, interval('8m'),     0),
            'script'             => setv(T_STRING, 0, 1, '/special/api.php', undef),
            'server'             => setv(T_FQDNP,  1, 0, 'dinahosting.com',  undef),
        },
    },
    'dnsmadeeasy' => {
        'updateable' => undef,
        'update'     => \&nic_dnsmadeeasy_update,
        'examples'   => \&nic_dnsmadeeasy_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'script' => setv(T_STRING, 1, 1, '/servlet/updateip',  undef),
            'server' => setv(T_FQDNP,  1, 0, 'cp.dnsmadeeasy.com', undef),
        },
    },
    'dondominio' => {
        'updateable' => undef,
        'update'     => \&nic_dondominio_update,
        'examples'   => \&nic_dondominio_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'server' => setv(T_FQDNP, 1, 0, 'dondns.dondominio.com', undef),
        },
    },
    'dslreports1' => {
        'updateable' => undef,
        'update'     => \&nic_dslreports1_update,
        'examples'   => \&nic_dslreports1_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'server' => setv(T_FQDNP, 1, 0, 'www.dslreports.com', undef),
            'host' => setv(T_NUMBER, 1, 1, 0, undef),
        },
    },
    'domeneshop' => {
        'updateable' => undef,
        'update'     => \&nic_domeneshop_update,
        'examples'   => \&nic_domeneshop_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'server' => setv(T_FQDNP,  1, 0, 'api.domeneshop.no', undef),
        },
    },
    'duckdns' => {
        'updateable' => undef,
        'update'     => \&nic_duckdns_update,
        'examples'   => \&nic_duckdns_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'login'  => setv(T_LOGIN, 0, 0, 'unused',          undef),
            'server' => setv(T_FQDNP, 1, 0, 'www.duckdns.org', undef),
        },
    },
    'dyndns1' => {
        'updateable' => \&nic_dyndns2_updateable,
        'update'     => \&nic_dyndns1_update,
        'examples'   => \&nic_dyndns1_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            %{$variables{'dyndns-common-defaults'}},
        },
    },
    'dyndns2' => {
        'updateable' => \&nic_dyndns2_updateable,
        'update'     => \&nic_dyndns2_update,
        'examples'   => \&nic_dyndns2_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            %{$variables{'dyndns-common-defaults'}},
            'custom' => setv(T_BOOL,   0, 1, 0,             undef),
            'script' => setv(T_STRING, 1, 1, '/nic/update', undef),
        },
    },
    'easydns' => {
        'updateable' => undef,
        'update'     => \&nic_easydns_update,
        'examples'   => \&nic_easydns_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'backupmx'     => setv(T_BOOL,   0, 1, 0,                    undef),
            'min-interval' => setv(T_DELAY,  0, 0, interval('5m'),       0),
            'mx'           => setv(T_OFQDN,  0, 1, '',                   undef),
            'server'       => setv(T_FQDNP,  1, 0, 'api.cp.easydns.com', undef),
            'script'       => setv(T_STRING, 1, 1, '/dyn/generic.php',   undef),
            'wildcard'     => setv(T_BOOL,   0, 1, 0,                    undef),
        },
    },
    'freedns' => {
        'updateable' => undef,
        'update'     => \&nic_freedns_update,
        'examples'   => \&nic_freedns_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY, 0, 0, 0,                    interval('5m')),
            'server'       => setv(T_FQDNP, 1, 0, 'freedns.afraid.org', undef),
        },
    },
    'freemyip' => {
        'updateable' => undef,
        'update'     => \&nic_freemyip_update,
        'examples'   => \&nic_freemyip_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'login'  => setv(T_LOGIN, 0, 0, 'unused',       undef),
            'server' => setv(T_FQDNP, 1, 0, 'freemyip.com', undef),
        },
    },
    'gandi' => {
        'updateable' => undef,
        'update'     => \&nic_gandi_update,
        'examples'   => \&nic_gandi_examples,
        'variables'  => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY,  0, 0, 0,               interval('5m')),
            'server'       => setv(T_FQDNP,  1, 0, 'api.gandi.net', undef),
            'script'       => setv(T_STRING, 1, 1, '/v5',           undef),
            'ttl'          => setv(T_DELAY,  0, 0, undef,           interval('5m')),
            'zone'         => setv(T_FQDN,   1, 0, undef,           undef),
            # Unused variables.
            'login'        => setv(T_STRING, 0, 0, 'unused', undef),
        }
    },
    'godaddy' => {
        'updateable' => undef,
        'update'     => \&nic_godaddy_update,
        'examples'   => \&nic_godaddy_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY,  0, 0, interval('5m'),                 0),
            'server'       => setv(T_FQDNP,  1, 0, 'api.godaddy.com/v1/domains',   undef),
            'ttl'          => setv(T_NUMBER, 1, 0, 600,                            undef),
            'zone'         => setv(T_FQDN,   1, 0, '',                             undef),
        },
    },
    'googledomains' => {
        'updateable' => undef,
        'update'     => \&nic_googledomains_update,
        'examples'   => \&nic_googledomains_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY, 0, 0, interval('5m'),       0),
            'server'       => setv(T_FQDNP, 1, 0, 'domains.google.com', undef),
        },
    },
    'hetzner' => {
        'updateable' => undef,
        'update'     => \&nic_hetzner_update,
        'examples'   => \&nic_hetzner_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'login'        => setv(T_LOGIN,  0, 0, 'token',                        undef),
            'min-interval' => setv(T_DELAY,  0, 0, interval('1m'),                 0),
            'server'       => setv(T_FQDNP,  1, 0, 'dns.hetzner.com/api/v1',       undef),
            'ttl'          => setv(T_NUMBER, 0, 0, 60,                             60),
            'zone'         => setv(T_FQDN,   1, 0, '',                             undef),
        },
    },
    'mythicdyn' => {
        'updateable' => undef,
        'update'     => \&nic_mythicdyn_update,
        'examples'   => \&nic_mythicdyn_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY, 0, 0, interval('5m'),       0),
            'server'       => setv(T_FQDNP, 1, 0, 'api.mythic-beasts.com', undef),
        },
    },
    'namecheap' => {
        'updateable' => undef,
        'update'     => \&nic_namecheap_update,
        'examples'   => \&nic_namecheap_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY, 0, 0, 0, interval('5m')),
            'server'       => setv(T_FQDNP, 1, 0, 'dynamicdns.park-your-domain.com', undef),
        },
    },
    'nfsn' => {
        'updateable' => undef,
        'update'     => \&nic_nfsn_update,
        'examples'   => \&nic_nfsn_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min_interval' => setv(T_FQDNP,  0, 0, 0,                          interval('5m')),
            'server'       => setv(T_FQDNP,  1, 0, 'api.nearlyfreespeech.net', undef),
            'ttl'          => setv(T_NUMBER, 1, 0, 300,                        undef),
            'zone'         => setv(T_FQDN,   1, 0, undef,                      undef),
        },
    },
    'njalla' => {
        'updateable' => undef,
        'update'     => \&nic_njalla_update,
        'examples'   => \&nic_njalla_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'login' => setv(T_STRING, 0, 0, 'unused', undef),
            'server' => setv(T_FQDNP, 1, 0, 'njal.la', undef),
            'quietreply' => setv(T_BOOL, 0, 1, 0,      undef)
        },
    },
    'noip' => {
        'updateable' => undef,
        'update'     => \&nic_noip_update,
        'examples'   => \&nic_noip_examples,
        'variables' => {
            'atime'                     => setv(T_NUMBER, 0, 1, 0,               undef),
            'custom'                    => setv(T_BOOL,   0, 1, 0,               undef),
            'host'                      => setv(T_STRING, 1, 1, '',              undef),
            'ip'                        => setv(T_IP,     0, 1, undef,           undef),
            'login'                     => setv(T_LOGIN,  1, 0, '',              undef),
            'max-interval'              => setv(T_DELAY,  0, 0, interval('25d'), 0),
            'min-error-interval'        => setv(T_DELAY,  0, 0, interval('5m'),  0),
            'min-interval'              => setv(T_DELAY,  0, 0, interval('30s'), 0),
            'mtime'                     => setv(T_NUMBER, 0, 1, 0,               undef),
            'password'                  => setv(T_PASSWD, 1, 0, '',              undef),
            'server'                    => setv(T_FQDNP,  1, 0, 'dynupdate.no-ip.com', undef),
            'static'                    => setv(T_BOOL,   0, 1, 0,               undef),
            'status'                    => setv(T_ANY,    0, 1, '',              undef),
            'warned-min-error-interval' => setv(T_ANY,    0, 1, 0,               undef),
            'warned-min-interval'       => setv(T_ANY,    0, 1, 0,               undef),
            'wtime'                     => setv(T_DELAY,  0, 1, 0,               interval('30s')),
        },
    },
    'nsupdate' => {
        'updateable' => undef,
        'update'     => \&nic_nsupdate_update,
        'examples'   => \&nic_nsupdate_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'login' => setv(T_LOGIN,  1, 0, '/usr/bin/nsupdate', undef),
            'tcp'   => setv(T_BOOL,   0, 1, 0,                   undef),
            'ttl'   => setv(T_NUMBER, 0, 1, 600,                 undef),
            'zone'  => setv(T_STRING, 1, 1, '',                  undef),
        },
    },
    'ovh' => {
        'updateable' => undef,
        'update'     => \&nic_ovh_update,
        'examples'   => \&nic_ovh_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'login'    => setv(T_LOGIN,  1, 0, '',            undef),
            'password' => setv(T_PASSWD, 1, 0, '',            undef),
            'script'   => setv(T_STRING, 1, 1, '/nic/update', undef),
            'server'   => setv(T_FQDNP,  1, 0, 'www.ovh.com', undef),
        },
    },
    'porkbun' => {
        'updateable' => undef,
        'update'     => \&nic_porkbun_update,
        'examples'   => \&nic_porkbun_examples,
        'variables'  => {
            'apikey'         => setv(T_PASSWD, 1, 0, '',         undef),
            'secretapikey'   => setv(T_PASSWD, 1, 0, '',         undef),
            'on-root-domain' => setv(T_BOOL,   0, 0, 0,          undef),
            'login'          => setv(T_LOGIN,  0, 0, 'unused',   undef),
            'password'       => setv(T_PASSWD, 0, 0, 'unused',   undef),
            'use'            => setv(T_USE,    0, 0, 'disabled', undef),
            'usev4'          => setv(T_USEV4,  0, 0, 'disabled', undef),
            'usev6'          => setv(T_USEV6,  0, 0, 'disabled', undef),
        },
    },
    'sitelutions' => {
        'updateable' => undef,
        'update'     => \&nic_sitelutions_update,
        'examples'   => \&nic_sitelutions_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'server'       => setv(T_FQDNP, 1, 0, 'www.sitelutions.com', undef),
            'min-interval' => setv(T_DELAY, 0, 0, 0,                     interval('5m')),
        },
    },
    'woima' => {
        'updateable' => undef,
        'update'     => \&nic_woima_update,
        'examples'   => \&nic_woima_examples,
        'variables' => {
            'atime'                     => setv(T_NUMBER, 0, 1, 0,               undef),
            'backupmx'                  => setv(T_BOOL,   0, 1, 0,               undef),
            'custom'                    => setv(T_BOOL,   0, 1, 0,               undef),
            'ip'                        => setv(T_IP,     0, 1, undef,           undef),
            'login'                     => setv(T_LOGIN,  1, 0, '',              undef),
            'max-interval'              => setv(T_DELAY,  0, 0, interval('25d'), 0),
            'min-error-interval'        => setv(T_DELAY,  0, 0, interval('5m'),  0),
            'min-interval'              => setv(T_DELAY,  0, 0, interval('30s'), 0),
            'mtime'                     => setv(T_NUMBER, 0, 1, 0,               undef),
            'mx'                        => setv(T_OFQDN,  0, 1, '',              undef),
            'password'                  => setv(T_PASSWD, 1, 0, '',              undef),
            'script'                    => setv(T_STRING, 1, 1, '/nic/update',   undef),
            'server'                    => setv(T_FQDNP,  1, 0, 'dyn.woima.fi',  undef),
            'static'                    => setv(T_BOOL,   0, 1, 0,               undef),
            'status'                    => setv(T_ANY,    0, 1, '',              undef),
            'warned-min-error-interval' => setv(T_ANY,    0, 1, 0,               undef),
            'warned-min-interval'       => setv(T_ANY,    0, 1, 0,               undef),
            'wildcard'                  => setv(T_BOOL,   0, 1, 0,               undef),
            'wtime'                     => setv(T_DELAY,  0, 1, 0,               interval('30s')),
        },
    },
    'yandex' => {
        'updateable' => undef,
        'update'     => \&nic_yandex_update,
        'examples'   => \&nic_yandex_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY, 0, 0, interval('5m'),     0),
            'server'       => setv(T_FQDNP, 1, 0, 'pddimp.yandex.ru', undef),
        },
    },
    'zoneedit1' => {
        'updateable' => undef,
        'update'     => \&nic_zoneedit1_update,
        'examples'   => \&nic_zoneedit1_examples,
        'variables' => {
            %{$variables{'service-common-defaults'}},
            'min-interval' => setv(T_DELAY, 0, 0, interval('10m'),        0),
            'server'       => setv(T_FQDNP, 1, 0, 'dynamic.zoneedit.com', undef),
            'zone'         => setv(T_OFQDN, 0, 0, undef,                  undef),
        },
    },
    'keysystems' => {
        'updateable' => undef,
        'update' => \&nic_keysystems_update,
        'examples'  => \&nic_keysystems_examples,
        'variables' => merge(
            $variables{'keysystems-common-defaults'},
            $variables{'service-common-defaults'},
        ),
    },
    'dnsexit2' => {
        'updateable' => undef,
        'update'     => \&nic_dnsexit2_update,
        'examples'   => \&nic_dnsexit2_examples,
        'variables'  => {
            %{$variables{'service-common-defaults'}},
            %{$variables{'dnsexit2-common-defaults'}},
            # nic_updateable() assumes that every service uses a username/login but that is
            # not true for the DNSExit API. Silence warnings by redefining the username variable
            # as non-required with value unused.
            'login'  => setv(T_STRING, 0, 0, 'unused', undef),
        },
    },
    'regfishde' => {
        'updateable' => undef,
        'update'     => \&nic_regfishde_update,
        'examples'   => \&nic_regfishde_examples,
        'variables'  => merge(
            $variables{'regfishde-common-defaults'},
            $variables{'service-common-defaults'},
        ),
    },
    'enom' => {
        'updateable' => undef,
        'update'     => \&nic_enom_update,
        'examples'   => \&nic_enom_examples,
        'variables'  => {
            %{$variables{'service-common-defaults'}},
            'server'       => setv(T_FQDNP,  1, 0, 'dynamic.name-services.com', undef),
            'min-interval' => setv(T_DELAY,  0, 0, 0, interval('5m')),
         },
     },
    'infomaniak' => {
        'updateable' => undef,
        'update'     => \&nic_infomaniak_update,
        'examples'   => \&nic_infomaniak_examples,
        'variables'  => {
            %{$variables{'service-common-defaults'}},
        },
    },
);
$variables{'merged'} = {
    map({ %{$services{$_}{'variables'}} } keys(%services)),
    %{$variables{'dyndns-common-defaults'}},
    %{$variables{'service-common-defaults'}},
    %{$variables{'global-defaults'}},
};

# This will hold the processed args.
my %opt = ();
my $deprecated_handler = sub { warning("'-$_[0]' is deprecated and does nothing"); };
$opt{'fw-banlocal'} = $deprecated_handler;
$opt{'if-skip'} = $deprecated_handler;
$opt{'list-devices'} = sub {
    printf("%s %s\n", $_, $builtinfw{$_}{name}) for sort(keys(%builtinfw));
    exit(0);
};
$opt{'list-protocols'} = sub {
    printf("%s\n", $_) for sort(keys(%services));
    exit(0);
};
$opt{'list-web-services'} = sub {
    printf("%s %s\n", $_, $builtinweb{$_}{url}) for sort(keys(%builtinweb));
    exit(0);
};

my @opt = (
    "usage: ${program} [options]",
    "options are:",
    ["daemon",            "=s", "-daemon <delay>       : run as a daemon, specify <delay> as an interval"],
    ["foreground",        "!",  "-foreground           : do not fork"],
    ["proxy",             "=s", "-proxy <host>         : use <host> as the HTTP proxy"],
    ["server",            "=s", "-server <host>        : update DNS information on <host>"],
    ["protocol",          "=s", "-protocol <type>      : update protocol used"],
    ["list-protocols",    "",   "-list-protocols       : print a machine-readable list of supported update protocols and exit. Format: one per line"],
    ["file",              "=s", "-file <path>          : load configuration information from <path>"],
    ["cache",             "=s", "-cache <path>         : record address used in <path>"],
    ["pid",               "=s", "-pid <path>           : record process id in <path> if daemonized"],
    "",
    ["use",               "=s", "-use <which>          : deprecated, see 'usev4' and 'usev6'"],
    &ip_strategies_usage(),
    [ "usev4",       "=s", "-usev4 <which>             : how the should IPv4 address be obtained."],
    &ipv4_strategies_usage(),
    [ "usev6",       "=s", "-usev6 <which>             : how the should IPv6 address be obtained."],
    &ipv6_strategies_usage(),
    "",
    "  Options that apply to 'use=ip':",
    ["ip",                "=s", "-ip <address>         : deprecated, use 'ipv4' or 'ipv6'"],
    ["ipv4",              "=s", "-ipv4 <address>       : set the IPv4 address to <address>"],
    ["ipv6",              "=s", "-ipv6 <address>       : set the IPv6 address to <address>"],
    "",
    "  Options that apply to 'use=if':",
    ["if",                "=s", "-if <interface>       : deprecated, use 'ifv4' or 'ifv6'"],
    ["ifv4",              "=s", "-ifv4 <interface>     : obtain IPv4 address from <interface>"],
    ["ifv6",              "=s", "-ifv6 <interface>     : obtain IPv6 address from <interface>"],
    "",
    "  Options that apply to 'use=web':",
    ["web",               "=s", "-web <service>|<url>  : deprecated, use 'webv4' or 'webv6'"],
    ["web-skip",          "=s", "-web-skip <pattern>   : deprecated, use 'webv4-skip' or 'webv6-skip'"],
    ["webv4",             "=s", "-webv4 <service>|<url>: obtain IPv4 address from a web-based IP discovery service, either a known <service> or a custom <url>"],
    ["webv4-skip",        "=s", "-webv4-skip <pattern> : skip any IP addresses before <pattern> in the output of 'ip address show dev <interface>' (or 'ifconfig <interface>')"],
    ["webv6",             "=s", "-webv6 <service>|<url>: obtain IPv6 address from a web-based IP discovery service, either a known <service> or a custom <url>"],
    ["webv6-skip",        "=s", "-webv6-skip <pattern> : skip any IP addresses before <pattern> in the output of 'ip address show dev <interface>' (or 'ifconfig <interface>')"],
    ["list-web-services", "",   "-list-web-services    : print a machine-readable list of web-based IP discovery services for use with 'web=<service>' and exit. Format: one service per line, each line has the form '<service> <url>'"],
    "",
    "  Options that apply to 'use=fw' and 'use=<device>':",
    ["fw",                "=s", "-fw <address>|<url>   : deprecated, use 'fwv4' or 'fwv6'"],
    ["fw-skip",           "=s", "-fw-skip <pattern>    : deprecated, use 'fwv4-skip' or 'fwv6-skip'"],
    ["fwv4",              "=s", "-fwv4 <address>|<url> : obtain IPv4 address from device with IP address <address> or URL <url>"],
    ["fwv4-skip",         "=s", "-fwv4-skip <pattern>  : skip any IP addresses before <pattern> in the text returned from the device"],
    ["fwv6",              "=s", "-fwv6 <address>|<url> : obtain IPv6 address from device with IP address <address> or URL <url>"],
    ["fwv6-skip",         "=s", "-fwv6-skip <pattern>  : skip any IP addresses before <pattern> in the text returned from the device"],
    ["fw-login",          "=s", "-fw-login <login>     : use <login> when getting the IP from the device"],
    ["fw-password",       "=s", "-fw-password <secret> : use password <secret> when getting the IP from the device"],
    ["list-devices",      "",   "-list-devices         : print a machine-readable list of supported firewall/router devices and exit. Format: one device per line, each line has the form '<device> <description>'"],
    "",
    "  Options that apply to 'use=cmd':",
    ["cmd",               "=s", "-cmd <command>        : deprecated, use 'cmdv4' or 'cmdv6'"],
    ["cmd-skip",          "=s", "-cmd-skip <pattern>   : deprecated, filter in program wrapper script"],
    ["cmdv4",             "=s", "-cmdv4 <command>      : obtain IPv4 address from the output of <command>"],
    ["cmdv6",             "=s", "-cmdv6 <command>      : obtain IPv6 address from the output of <command>"],
    "",
    ["login",             "=s", "-login <user>         : log in to the dynamic DNS service as <user>"],
    ["password",          "=s", "-password <secret>    : log in to the dynamic DNS service with password <secret>"],
    ["host",              "=s", "-host <host>          : update DNS information for <host>"],
    "",
    ["options",           "=s", "-options <opt>=<val>[,<opt>=<val>,...]\n                        : optional per-service arguments (see below)"],
    "",
    ["ssl",               "!",  "-{no}ssl              : do updates over encrypted SSL connection"],
    ["ssl_ca_dir",        "=s", "-ssl_ca_dir <dir>     : look in <dir> for certificates of trusted certificate authorities (default: auto-detect)"],
    ["ssl_ca_file",       "=s", "-ssl_ca_file <file>   : look at <file> for certificates of trusted certificate authorities (default: auto-detect)"],
    ["fw-ssl-validate",   "!", "-{no}fw-ssl-validate   : Validate SSL certificate when retrieving IP address from firewall"],
    ["web-ssl-validate",  "!","-{no}web-ssl-validate   : Validate SSL certificate when retrieving IP address from web"],
    ["retry",             "!",  "-{no}retry            : retry failed updates"],
    ["force",             "!",  "-{no}force            : force an update even if the update may be unnecessary"],
    ["timeout",           "=i", "-timeout <max>        : when fetching a URL, wait at most <max> seconds for a response"],
    ["syslog",            "!",  "-{no}syslog           : log messages to syslog"],
    ["facility",          "=s", "-facility <type>      : log messages to syslog to facility <type>"],
    ["priority",          "=s", "-priority <pri>       : log messages to syslog with priority <pri>"],
    ["max-warn",          "=i", "-max-warn <max>       : log at most <max> warning messages for undefined IP address"],
    ["mail",              "=s", "-mail <address>       : e-mail messages to <address>"],
    ["mail-failure",      "=s", "-mail-failure <addr>  : e-mail messages for failed updates to <addr>"],
    ["exec",              "!",  "-{no}exec             : do {not} execute; just show what would be done"],
    ["debug",             "!",  "-{no}debug            : print {no} debugging information"],
    ["verbose",           "!",  "-{no}verbose          : print {no} verbose information"],
    ["quiet",             "!",  "-{no}quiet            : print {no} messages for unnecessary updates"],
    ["help",              "",   "-help                 : display this message and exit"],
    ["postscript",        "",   "-postscript           : script to run after updating ddclient, has new IP as param"],
    ["query",             "!",  "-{no}query            : print {no} ip addresses and exit"],
    ["fw-banlocal",       "!",  ""], ## deprecated
    ["if-skip",           "=s", ""], ## deprecated
    ["test",              "!",  ""], ## hidden
    ["geturl",            "=s", ""], ## hidden
    "",
    nic_examples(),
    "$program version $version, ",
    "  originally written by Paul Burry, paul+ddclient\@burry.ca",
    "  project now maintained on https://github.com/ddclient/ddclient"
);

sub main {
    ## process args
    my $opt_usage = process_args(@opt);
    $saved_cache = '';
    %saved_opt = %opt;
    $result = 'OK';

    test_geturl(opt('geturl')) if opt('geturl');

    if (opt('help')) {
        printf "%s\n", $opt_usage;
        exit 0;
    }

    ## read config file because 'daemon' mode may be defined there.
    read_config($opt{'file'} // default('file'), \%config, \%globals);
    init_config();
    test_possible_ip() if opt('query');

    my $caught_hup  = 0;
    my $caught_term = 0;
    my $caught_int  = 0;
    $SIG{'HUP'}  = sub { $caught_hup  = 1; };
    $SIG{'TERM'} = sub { $caught_term = 1; };
    $SIG{'INT'}  = sub { $caught_int  = 1; };
    # don't fork() if foreground
    if (opt('foreground')) {
        ;
    } elsif (opt('daemon')) {
        $SIG{'CHLD'} = 'IGNORE';
        my $pid = fork;
        if ($pid < 0) {
            print STDERR "${program}: can not fork ($!)\n";
            exit -1;
        } elsif ($pid) {
            exit 0;
        }
        $SIG{'CHLD'} = 'DEFAULT';
        open(STDOUT, ">/dev/null");
        open(STDERR, ">/dev/null");
        open(STDIN,  "</dev/null");
        write_pid();
    }

    umask 077;
    do {
        $now    = time;
        $result = 'OK';
        %opt    = %saved_opt;
        if (opt('help')) {
            *STDERR = *STDOUT;
            printf("Help found");
        }

        read_config($opt{'file'} // default('file'), \%config, \%globals);
        init_config();
        read_cache(opt('cache'), \%cache);
        print_info() if opt('debug') && opt('verbose');

        fatal("invalid argument '-use %s'; possible values are:\n%s", $opt{'use'}, join("\n", ip_strategies_usage()))
            unless exists $ip_strategies{lc opt('use')};
        if (defined($opt{'usev6'})) {
            usage("invalid argument '-usev6 %s'; possible values are:\n%s", $opt{'usev6'}, join("\n",ipv6_strategies_usage()))
                unless exists $ipv6_strategies{lc opt('usev6')};
        }

        $daemon = opt('daemon');

        update_nics();

        if ($daemon) {
            debug("sleep %s", $daemon);
            sendmail();

            my $left = $daemon;
            while (($left > 0) && !$caught_hup && !$caught_term && !$caught_int) {
                my $delay = $left > 10 ? 10 : $left;

                $0 = sprintf("%s - sleeping for %s seconds", $program, $left);
                $left -= sleep $delay;
                # preventing deep sleep - see [bugs:#46]
                if ($left > $daemon) {
                    $left = $daemon;
                }
            }
            $caught_hup = 0;
            $result     = 0;

        } elsif (!scalar(%config)) {
            warning("no hosts to update.") unless !opt('quiet') || opt('verbose') || !$daemon;
            $result = 1;

        } else {
            $result = $result eq 'OK' ? 0 : 1;
        }
    } while ($daemon && !$result && !$caught_term && !$caught_int);

    warning("caught SIGINT; exiting") if $caught_int;
    unlink_pid();
    sendmail();

    exit($result);
}

######################################################################
## runpostscript
######################################################################

sub runpostscript {
    my ($ip) = @_;

    if (defined $globals{postscript}) {
        my @postscript = split(/\s+/, $globals{postscript});
        if (-x $postscript[0]) {
            system("$globals{postscript} $ip &");
        } else {
            warning("Can not execute post script: %s", $globals{postscript});
        }
    }
}

######################################################################
## update_nics
######################################################################
sub update_nics {
    my %examined = ();
    my %iplist   = ();
    my %ipv4list = ();
    my %ipv6list = ();

    foreach my $s (sort keys %services) {
        my (@hosts, %ipsv4, %ipsv6) = ();
        my $updateable = $services{$s}{'updateable'};
        my $update     = $services{$s}{'update'};

        foreach my $h (sort keys %config) {
            next if $config{$h}{'protocol'} ne lc($s);
            $examined{$h} = 1;
            # we only do this once per 'use' and argument combination
            my $use       = opt('use',   $h) // 'disabled';
            my $usev4     = opt('usev4', $h) // 'disabled';
            my $usev6     = opt('usev6', $h) // 'disabled';
            $use          = 'disabled' if ($use eq 'no'); # backward compatibility
            $usev6        = 'disabled' if ($usev6 eq 'no'); # backward compatibility
            $use          = 'disabled' if ($usev4 ne 'disabled') || ($usev6 ne 'disabled');
            my $arg_ip    = opt('ip',    $h) // '';
            my $arg_ipv4  = opt('ipv4',  $h) // '';
            my $arg_ipv6  = opt('ipv6',  $h) // '';
            my $arg_fw    = opt('fw',    $h) // '';
            my $arg_fwv4  = opt('fwv4',  $h) // '';
            my $arg_fwv6  = opt('fwv6',  $h) // '';
            my $arg_if    = opt('if',    $h) // '';
            my $arg_ifv4  = opt('ifv4',  $h) // '';
            my $arg_ifv6  = opt('ifv6',  $h) // '';
            my $arg_web   = opt('web',   $h) // '';
            my $arg_webv4 = opt('webv4', $h) // '';
            my $arg_webv6 = opt('webv6', $h) // '';
            my $arg_cmd   = opt('cmd',   $h) // '';
            my $arg_cmdv4 = opt('cmdv4', $h) // '';
            my $arg_cmdv6 = opt('cmdv6', $h) // '';
            my $ip = undef;
            my $ipv4 = undef;
            my $ipv6 = undef;

            if ($use ne 'disabled') {
                if (exists $iplist{$use}{$arg_ip}{$arg_fw}{$arg_if}{$arg_web}{$arg_cmd}) {
                    # If we have already done a get_ip() for this, don't do it again.
                    $ip = $iplist{$use}{$arg_ip}{$arg_fw}{$arg_if}{$arg_web}{$arg_cmd};
                } else {
                    # Else need to find the IP address...
                    $ip = get_ip($use, $h);
                    if (is_ipv4($ip) || is_ipv6($ip)) {
                         # And if it is valid, remember it...
                        $iplist{$use}{$arg_ip}{$arg_fw}{$arg_if}{$arg_web}{$arg_cmd} = $ip;
                    } else {
                        warning("%s: unable to determine IP address with strategy use=%s", $h, $use)
                            if !$daemon || opt('verbose');
                    }
                }
                # And remember it as the IP address we want to send to the DNS service.
                $config{$h}{'wantip'} = $ip;
            }

            if ($usev4 ne 'disabled') {
                if (exists $ipv4list{$usev4}{$arg_ipv4}{$arg_fwv4}{$arg_ifv4}{$arg_webv4}{$arg_cmdv4}) {
                    # If we have already done a get_ipv4() for this, don't do it again.
                    $ipv4 = $ipv4list{$usev4}{$arg_ipv4}{$arg_fwv4}{$arg_ifv4}{$arg_webv4}{$arg_cmdv4};
                } else {
                    # Else need to find the IPv4 address...
                    $ipv4 = get_ipv4($usev4, $h);
                    if (is_ipv4($ipv4)) {
                         # And if it is valid, remember it...
                        $ipv4list{$usev4}{$arg_ipv4}{$arg_fwv4}{$arg_ifv4}{$arg_webv4}{$arg_cmdv4} = $ipv4;
                    } else {
                        warning("%s: unable to determine IPv4 address with strategy usev4=%s", $h, $usev4)
                            if !$daemon || opt('verbose');
                    }
                }
                # And remember it as the IPv4 address we want to send to the DNS service.
                $config{$h}{'wantipv4'} = $ipv4;
            }

            if ($usev6 ne 'disabled') {
                if (exists $ipv6list{$usev6}{$arg_ipv6}{$arg_fwv6}{$arg_ifv6}{$arg_webv6}{$arg_cmdv6}) {
                    # If we have already done a get_ipv6() for this, don't do it again.
                    $ipv6 = $ipv6list{$usev6}{$arg_ipv6}{$arg_fwv6}{$arg_ifv6}{$arg_webv6}{$arg_cmdv6};
                } else {
                    # Else need to find the IPv6 address...
                    $ipv6 = get_ipv6($usev6, $h);
                    if (is_ipv6($ipv6)) {
                        # And if it is valid, remember it...
                        $ipv6list{$usev6}{$arg_ipv6}{$arg_fwv6}{$arg_ifv6}{$arg_webv6}{$arg_cmdv6} = $ipv6;
                    } else {
                        warning("%s: unable to determine IPv6 address with strategy usev6=%s", $h, $usev6)
                            if !$daemon || opt('verbose');
                    }
                }
                # And remember it as the IP address we want to send to the DNS service.
                $config{$h}{'wantipv6'} = $ipv6;
            }

            # DNS service update functions should only have to handle 'wantipv4' and 'wantipv6'
            $config{$h}{'wantipv4'} = $ipv4 = $ip if (!$ipv4 && is_ipv4($ip));
            $config{$h}{'wantipv6'} = $ipv6 = $ip if (!$ipv6 && is_ipv6($ip));
            # But we will set 'wantip' to the IPv4 so old functions continue to work until we update them all
            $config{$h}{'wantip'}   = $ipv4       if (!$ip && $ipv4);

            if (!$ip && !$ipv4 && !$ipv6)
            {
                warning("Could not determine an IP for %s", $h);
                next;
            }

            next if !nic_updateable($h, $updateable);
            push @hosts, $h;

            $ipsv4{$ipv4} = $h if ($ipv4);
            $ipsv6{$ipv6} = $h if ($ipv6);
        }
        if (@hosts) {
            $0 = sprintf("%s - updating %s", $program, join(',', @hosts));
            &$update(@hosts);

            # Backwards compatibility:
            # The legacy 'use' parameter sets 'wantip' and the legacy providers process this and
            # set 'ip', 'status' accordingly.
            # The new 'usev*' parameters set 'wantipv*' and the new providers set 'ipv*' and 'status-ipv*'.
            # To allow gradual transition, we make sure both the old 'status' and 'ip' are being set
            # accordingly to what new providers returned in the new 'status-ipv*' and 'ipv*' fields respectively.
            foreach my $h (@hosts) {
                $config{$h}{'status'} //= $config{$h}{'status-ipv4'};
                $config{$h}{'status'} //= $config{$h}{'status-ipv6'};
                $config{$h}{'ip'} //= $config{$h}{'ipv4'};
                $config{$h}{'ip'} //= $config{$h}{'ipv6'};
            }

            runpostscript(join ' ', keys %ipsv4, keys %ipsv6);
        }
    }
    foreach my $h (sort keys %config) {
        if (!exists $examined{$h}) {
            failed("%s was not updated because protocol %s is not supported.",
                   $h, $config{$h}{'protocol'} // '<undefined>');
        }
    }
    write_cache(opt('cache'));
}

######################################################################
## unlink_pid()
######################################################################
sub unlink_pid {
    if (opt('pid') && opt('daemon')) {
        unlink opt('pid');
    }
}

######################################################################
## write_pid()
######################################################################
sub write_pid {
    my $file = opt('pid');

    if ($file && opt('daemon')) {
        local *FD;
        if (!open(FD, "> $file")) {
            warning("Cannot create file '%s'. (%s)", $file, $!);

        } else {
            printf FD "%s\n", $$;
            close(FD);
        }
    }
}

######################################################################
## write_cache($file)
######################################################################
sub write_cache {
    my ($file) = @_;

    ## merge the updated host entries into the cache.
    foreach my $h (keys %config) {
        if (!exists $cache{$h} || $config{$h}{'update'}) {
            map { defined($config{$h}{$_}) ? ($cache{$h}{$_} = $config{$h}{$_}) : () } @{$config{$h}{'cacheable'}};
        } else {
            map { $cache{$h}{$_} = $config{$h}{$_} } qw(atime wtime status);
        }
    }

    ## construct the cache file.
    my $cache = "";
    foreach my $h (sort keys %cache) {
        my $opt = join(',', map { "$_=" . ($cache{$h}{$_} // '') } sort keys %{$cache{$h}});

        $cache .= sprintf "%s%s%s\n", $opt, ($opt ? ' ' : ''), $h;
    }
    $file = '' if defined($saved_cache) && $cache eq $saved_cache;

    ## write the updates and other entries to the cache file.
    if ($file) {
        (undef, my $dir) = fileparse($file);
        make_path($dir, { error => \my $err }) if !-d $dir;
        if ($err && @$err) {
            for my $diag (@$err) {
                my ($f, $msg) = %$diag;
                warning("Failed to create cache file directory: %s: %s", $f, $msg);
            }
            return;
        }

        $saved_cache = undef;
        local *FD;
        if (!open(FD, ">", $file)) {
            warning("Failed to create cache file %s: %s", $file, $!);
            return;
        }
        printf FD "## %s-%s\n", $program, $version;
        printf FD "## last updated at %s (%d)\n", prettytime($now), $now;
        printf FD "%s", $cache;

        close(FD);
    }
}
######################################################################
## read_cache($file) - called before reading the .conf
######################################################################
sub read_cache {
    my $file    = shift;
    my $config  = shift;
    my $globals = {};

    %{$config} = ();
    ## read the cache file ignoring anything on the command-line.
    if (-e $file) {
        my %saved = %opt;
        %opt         = ();
        $saved_cache = _read_config($config, $globals, "##\\s*$program-$version\\s*", $file);
        %opt         = %saved;

        foreach my $h (keys %cache) {
            if (exists $config->{$h}) {
                foreach (qw(atime mtime wtime ip status)) {
                    $config->{$h}{$_} = $cache{$h}{$_} if exists $cache{$h}{$_};
                }
            }
        }
    }
}
######################################################################
## parse_assignments(string) return (rest, %variables)
## parse_assignment(string)  return (name, value, rest)
######################################################################
sub parse_assignments {
    my ($rest) = @_;
    my %variables = ();

    while (1) {
        (my $name, my $value, $rest) = parse_assignment($rest);
        $rest =~ s/^[,\s]+//;
        return ($rest, %variables) if !defined($name);
        if ($name eq 'fw-banlocal' || $name eq 'if-skip') {
            warning("'$name' is deprecated and does nothing");
            next;
        }
        $variables{$name} = $value;
    }
}
sub parse_assignment {
    my ($rest) = @_;
    my ($name, $value);
    my ($escape, $quote) = (0, '');

    if ($rest =~ /^[,\s]*([a-z][0-9a-z_-]*)=(.*)/i) {
        ($name, $rest, $value) = ($1, $2, '');

        while (length(my $c = substr($rest, 0, 1))) {
            if ($escape) {
                $value .= $c;
                $escape = 0;
            } elsif ($c eq "\\") {
                $escape = 1;
            } elsif ($quote && $c eq $quote) {
                $quote = '';
            } elsif (!$quote && $c =~ /[\'\"]/) {
                $quote = $c;
            } elsif (!$quote && $c =~ /^[\n\s,]/) {
                # The terminating character is not consumed.
                last;
            } else {
                $value .= $c;
            }
            $rest = substr($rest,1);
        }
    }
    warning("assignment to '%s' ended with the escape character (\\)", $name) if $escape;
    warning("assignment to '%s' ended with an unterminated quote (%s)", $name, $quote) if $quote;
    return ($name, $value, $rest);
}
######################################################################
## read_config
######################################################################
sub read_config {
    my ($file, $config, $globals) = @_;
    _read_config($config, $globals, '', $file);
}
sub _read_config {
    # Configuration line format after comment and continuation
    # removal:
    #
    #   [opt=value, ...] [host[, ...] [login [password]]]
    #
    # Details:
    #   - No whitespace is allowed around the '=' in opt=value.
    #   - An option name may only contain lowercase letters, numbers,
    #     underscore, and hyphen-minus, and must start with a letter.
    #   - A value or hostname is terminated by unquoted whitespace
    #     (including newline) or an unquoted comma followed by
    #     optional whitespace.
    #   - Values (but not hosts, login, or password) may contain
    #     quoted parts:
    #       - A backslash that itself is not quoted by another
    #         backslash quotes the next character.
    #       - An unquoted single quote quotes the subsequent
    #         non-backslash, non-newline characters until the next
    #         single quote.
    #       - An unquoted double quote quotes the subsequent
    #         non-backslash, non-newline characters until the next
    #         double quote.
    #   - login and password must not contain whitespace.
    #   - login must not start or end with a comma.
    #   - password must not start with a comma.
    #   - If no host is specified (either via a 'host=' option or
    #     after the options), the options are stored in %{$2}.
    #     Otherwise, the options are combined with the global values
    #     accumulated thus far and stored in $1->{$host} for each
    #     referenced host.

    my $config  = shift;
    my $globals = shift;
    my $stamp   = shift;
    local $file = shift;
    my %globals = ();
    my %config  = ();
    my $content = '';

    local *FD;
    if (!open(FD, "< $file")) {
        warning("Cannot open file '%s'. (%s)", $file, $!);
    }

    # If file is owned by our effective uid, ensure that it has no access for group or others.
    # Otherwise, require that it isn't writable when not owned by us. For example allow it to
    # be owned by root:ddclient with mode 640. Always ensure that it is not accessible to others.
    my ($dev, $ino, $mode, @statrest) = stat(FD);
    if ($mode & 077 && -o FD) {
        if (-f FD && (chmod 0600, $file)) {
            warning("file $file must be accessible only by its owner (fixed).");
        }
        warning("file $file must be accessible only by its owner.");
    } elsif (! -o FD && -w FD) {
        warning("file $file should be owned only by ddclient or not be writable.");
    }
    if ($mode & 07) {
        warning("file $file must not be accessible by others.");
    }

    local $lineno = 0;
    my $continuation = '';
    my %passwords    = ();
    while (<FD>) {
        s/[\r\n]//g;

        $lineno++;

        ## check for the program version stamp
        if (($. == 1) && $stamp && ($_ !~ /^$stamp$/i)) {
            warning("program version mismatch; ignoring %s", $file);
            last;
        }
        if (/\\\s+$/) {
            warning("whitespace follows the \\ at the end-of-line.\nIf you meant to have a line continuation, remove the trailing whitespace.");
        }

        $content .= "$_\n" unless /^#/;

        ## parsing passwords is special
        if (/^([^#]*\s)?([^#]*?password)\s*=\s*('.*'|[^']\S*)(.*)/) {
            my ($head, $key, $value, $tail) = ($1 // '', $2, $3, $4);
            $value = $1 if $value =~ /^'(.*)'$/;
            $passwords{$key} = $value;
            $_ = "${head}${key}=dummy${tail}";
        }

        ## remove comments
        s/#.*//;

        ## handle continuation lines
        $_ = "$continuation$_";
        if (/\\$/) {
            chop;
            $continuation = $_;
            next;
        }
        $continuation = '';

        s/^\s+//;     # remove leading white space
        s/\s+$//;     # remove trailing white space
        s/\s+/ /g;    # canonify
        next if /^$/;

        my %locals;
        ($_, %locals) = parse_assignments($_);
        s/\s*,\s*/,/g;
        my @args = split;

        ## verify that keywords are valid...and check the value
        foreach my $k (keys %locals) {
            # Handle '_env' keyword suffix
            if ($k =~ /(.*)_env$/)
            {
                debug("Loading value for $1 from environment variable $locals{$k}.");
                if (exists($ENV{$locals{$k}}))
                {
                    # Set the value to the value of the environment variable
                    $locals{$1} = $ENV{$locals{$k}};
                    # Remove the '_env' suffix from the key
                    $k = $1;
                }
                else
                {
                    warning("Environment variable '$locals{$k}' not set for keyword '$k' (ignored)");
                    delete $locals{$k};
                    next;
                }
            }

            $locals{$k} = $passwords{$k} if defined $passwords{$k};
            if (!exists $variables{'merged'}{$k}) {
                warning("unrecognized keyword '%s' (ignored)", $k);
                delete $locals{$k};
            } else {
                my $def = $variables{'merged'}{$k};
                my $value = check_value($locals{$k}, $def);
                if (!defined($value)) {
                    warning("Invalid Value for keyword '%s' = '%s'", $k, $locals{$k});
                    delete $locals{$k};
                } else { $locals{$k} = $value; }
            }
        }
        if (exists($locals{'host'})) {
            $args[0] = @args ? "$args[0],$locals{host}" : "$locals{host}";
        }
        ## accumulate globals
        if ($#args < 0) {
            map { $globals{$_} = $locals{$_} } keys %locals;
        }

        ## process this host definition
        if (@args) {
            my ($host, $login, $password) = @args;

            ## add in any globals..
            %locals = %{merge(\%locals, \%globals)};

            ## override login and password if specified the old way.
            $locals{'login'}    = $login    if defined $login;
            $locals{'password'} = $password if defined $password;

            ## allow {host} to be a comma separated list of hosts
            foreach my $h (split_by_comma($host)) {
                if ($config{$h}) {
                    ## host already defined, merging configs
                    $config{$h} = { %{merge($config{$h}, \%locals)} };
                } else {
                    ## save a copy of the current globals
                    $config{$h} = { %locals };
                    $config{$h}{'host'} = $h;
                }
            }
        }
        %passwords = ();
    }
    close(FD);

    warning("file ends while expecting a continuation line.")
        if $continuation;

    %$globals = %globals;
    %$config  = %config;

    return $content;
}
######################################################################
## init_config -
######################################################################
sub init_config {
    %opt = %saved_opt;

    ##
    $opt{'quiet'} = 0 if opt('verbose');

    ## infer the IP strategy if possible
    if (!$opt{'use'}) {
        $opt{'use'} = 'web' if ($opt{'web'});
        $opt{'use'} = 'if'  if ($opt{'if'});
        $opt{'use'} = 'ip'  if ($opt{'ip'});
    }
    ## infer the IPv4 strategy if possible
    if (!$opt{'usev4'}) {
        $opt{'usev4'} = 'webv4' if ($opt{'webv4'});
        $opt{'usev4'} = 'ifv4'  if ($opt{'ifv4'});
        $opt{'usev4'} = 'ipv4'  if ($opt{'ipv4'});
    }
    ## infer the IPv6 strategy if possible
    if (!$opt{'usev6'}) {
        $opt{'usev6'} = 'webv6' if ($opt{'webv6'});
        $opt{'usev6'} = 'ifv6'  if ($opt{'ifv6'});
        $opt{'usev6'} = 'ipv6'  if ($opt{'ipv6'});
    }

    ## sanity check
    $opt{'max-interval'}       = min(interval(opt('max-interval')), interval(default('max-interval')));
    $opt{'min-interval'}       = max(interval(opt('min-interval')), interval(default('min-interval')));
    $opt{'min-error-interval'} = max(interval(opt('min-error-interval')), interval(default('min-error-interval')));

    $opt{'timeout'} = 0 if opt('timeout') < 0;

    ## parse an interval expression (such as '5m') into number of seconds
    $opt{'daemon'} = interval(opt('daemon')) if defined($opt{'daemon'});
    ## make sure the interval isn't too short
    $opt{'daemon'} = minimum('daemon') if opt('daemon') > 0 && opt('daemon') < minimum('daemon');

    ## define or modify host options specified on the command-line
    if (exists $opt{'options'} && defined $opt{'options'}) {
        ## collect cmdline configuration options.
        my %options = ();
        foreach my $opt (split_by_comma($opt{'options'})) {
            my ($name, $var) = split /\s*=\s*/, $opt;
            if ($name eq 'fw-banlocal' || $name eq 'if-skip') {
                warning("'$name' is deprecated and does nothing");
                next;
            }
            $options{$name} = $var;
        }
        ## determine hosts specified with -host
        my @hosts = ();
        if (exists $opt{'host'}) {
            foreach my $h (split_by_comma($opt{'host'})) {
                push @hosts, $h;
            }
        }
        ## and those in -options=...
        if (exists $options{'host'}) {
            foreach my $h (split_by_comma($options{'host'})) {
                push @hosts, $h;
            }
            delete $options{'host'};
        }
        ## merge options into host definitions or globals
        if (@hosts) {
            foreach my $h (@hosts) {
                $config{$h} = merge(\%options, $config{$h});
            }
            $opt{'host'} = join(',', @hosts);
        } else {
            %globals = %{merge(\%options, \%globals)};
        }
    }

    ## override global options with those on the command-line.
    foreach my $o (keys %opt) {
        if (defined $opt{$o} && exists $variables{'global-defaults'}{$o}) {
            $globals{$o} = $opt{$o};
        }
    }

    ## sanity check
    if (defined $opt{'host'} && defined $opt{'retry'}) {
        fatal("options -retry and -host (or -option host=..) are mutually exclusive");
    }

    ## determine hosts to update (those on the cmd-line, config-file, or failed cached)
    my @hosts = keys %config;
    if (opt('host')) {
        @hosts = split_by_comma($opt{'host'});
    }
    if (opt('retry')) {
        @hosts = map { $_ if $cache{$_}{'status'} ne 'good' } keys %cache;
    }

    ## remove any other hosts
    my %hosts;
    map { $hosts{$_} = undef } @hosts;
    map { delete $config{$_} unless exists $hosts{$_} } keys %config;

    ## collect the cacheable variables.
    foreach my $proto (keys %services) {
        my @cacheable = ();
        foreach my $k (keys %{$services{$proto}{'variables'}}) {
            push @cacheable, $k if $services{$proto}{'variables'}{$k}{'cache'};
        }
        $services{$proto}{'cacheable'} = [ @cacheable ];
    }

    ## sanity check..
    ## make sure config entries have all defaults and they meet minimums
    ## first the globals...
    foreach my $k (keys %globals) {
        my $def    = $variables{'merged'}{$k};
        my $ovalue = $globals{$k} // $def->{'default'};
        my $value  = check_value($ovalue, $def);
        if ($def->{'required'} && !defined $value) {
            $value = default($k);
            warning("'%s=%s' is an invalid %s. (using default of %s)", $k, $ovalue, $def->{'type'}, $value);
        }
        $globals{$k} = $value;
    }

    ## now the host definitions...
  HOST:
    foreach my $h (keys %config) {
        my $proto;
        $proto = $config{$h}{'protocol'};
        $proto = opt('protocol') if !defined($proto);

        load_sha1_support($proto) if (grep (/^$proto$/, ("freedns", "nfsn")));
        load_json_support($proto) if (grep (/^$proto$/, ("1984", "cloudflare", "digitalocean", "gandi", "godaddy", "hetzner", "yandex", "nfsn", "njalla", "porkbun", "dnsexit2")));

        if (!exists($services{$proto})) {
            warning("skipping host: %s: unrecognized protocol '%s'", $h, $proto);
            delete $config{$h};

        } else {
            my $svars = $services{$proto}{'variables'};
            my $conf  = { 'protocol' => $proto };

            foreach my $k (keys %$svars) {
                my $def    = $svars->{$k};
                my $ovalue = $config{$h}{$k} // $def->{'default'};
                my $value  = check_value($ovalue, $def);
                if ($def->{'required'} && !defined $value) {
                    warning("skipping host: %s: '%s=%s' is an invalid %s.", $h, $k, $ovalue, $def->{'type'});
                    delete $config{$h};
                    next HOST;
                }
                $conf->{$k} = $value;

            }
            $config{$h} = $conf;
            $config{$h}{'cacheable'} = [ @{$services{$proto}{'cacheable'}} ];
        }
    }
}

######################################################################
## process_args -
######################################################################
sub process_args {
    my @spec  = ();
    my $usage = "";

    foreach (@_) {
        if (ref $_) {
            my ($key, $specifier, $arg_usage) = @$_;
            my $value = default($key);

            ## add a option specifier
            push @spec, $key . $specifier;

            ## define the default value which can be overwritten later
            $opt{$key} = undef unless exists($opt{$key});

            next unless $arg_usage;

            ## add a line to the usage;
            $usage .= "  $arg_usage";
            if (defined($value) && $value ne '') {
                $usage .= " (default: ";
                if ($specifier eq '!') {
                    $usage .= "no" if ($specifier eq '!') && !$value;
                    $usage .= $key;
                } else {
                    $usage .= $value;
                }
                $usage .= ")";
            }
            $usage .= ".";
        } else {
            $usage .= $_;
        }
        $usage .= "\n";
    }
    ## process the arguments
    if (!GetOptions(\%opt, @spec)) {
        $opt{"help"} = 1;
    }
    return $usage;
}

######################################################################
## test_possible_ip - print possible IPs
######################################################################
sub test_possible_ip {
    local $opt{'debug'} = 0;

    printf "----- Test_possible_ip with 'get_ip' -----\n";
    printf "use=ip, ip=%s address is %s\n", opt('ip'), get_ip('ip') // 'NOT FOUND'
        if defined opt('ip');

    {
        local $opt{'use'} = 'if';
        # Note: The `ip` command adds a `@eth0` suffix to the names of VLAN
        # interfaces. That `@eth0` suffix is NOT part of the interface name.
        my @ifs = map({ /^[^\s:]*:\s*([^\s:@]+)/ ? $1 : () }
                      `command -v ip >/dev/null && ip -o link show`);
        @ifs = map({ /^([a-zA-Z].*?)(?::?\s.*)?$/ ? $1 : () }
                   `command -v ifconfig >/dev/null && ifconfig -a`) if $? || !@ifs;
        @ifs = () if $?;
        warning("failed to get list of interfaces") if !@ifs;
        foreach my $if (@ifs) {
            local $opt{'if'} = $if;
            printf "use=if, if=%s address is %s\n", opt('if'), get_ip('if') // 'NOT FOUND';
        }
    }
    if (opt('fw')) {
        if (opt('fw') !~ m%/%) {
            foreach my $fw (sort keys %builtinfw) {
                local $opt{'use'} = $fw;
                printf "use=%s address is %s\n", $fw, get_ip($fw) // 'NOT FOUND';
            }
        }
        local $opt{'use'} = 'fw';
        printf "use=fw, fw=%s address is %s\n", opt('fw'), get_ip(opt('fw')) // 'NOT FOUND'
            if !exists $builtinfw{opt('fw')};

    }
    {
        local $opt{'use'} = 'web';
        foreach my $web (sort keys %builtinweb) {
            local $opt{'web'} = $web;
            printf "use=web, web=%s address is %s\n", $web, get_ip('web') // 'NOT FOUND';
        }
        printf "use=web, web=%s address is %s\n", opt('web'), get_ip('web') // 'NOT FOUND'
            if !exists $builtinweb{opt('web')};
    }
    if (opt('cmd')) {
        local $opt{'use'} = 'cmd';
        printf "use=cmd, cmd=%s address is %s\n", opt('cmd'), get_ip('cmd') // 'NOT FOUND';
    }

    # Now force IPv4
    printf "----- Test_possible_ip with 'get_ipv4' ------\n";
    printf "use=ipv4, ipv4=%s address is %s\n", opt('ipv4'), get_ipv4('ipv4') // 'NOT FOUND'
        if defined opt('ipv4');

    {
        # Note: The `ip` command adds a `@eth0` suffix to the names of VLAN
        # interfaces. That `@eth0` suffix is NOT part of the interface name.
        my @ifs = map({ /^[^\s:]*:\s*([^\s:@]+)/ ? $1 : () }
                      `command -v ip >/dev/null && ip -o link show`);
        @ifs = map({ /^([a-zA-Z].*?)(?::?\s.*)?$/ ? $1 : () }
                   `command -v ifconfig >/dev/null && ifconfig -a`) if $? || !@ifs;
        @ifs = () if $?;
        warning("failed to get list of interfaces") if !@ifs;
        foreach my $if (@ifs) {
            local $opt{'ifv4'} = $if;
            printf "use=ifv4, ifv4=%s address is %s\n", opt('ifv4'), get_ipv4('ifv4') // 'NOT FOUND';
        }
    }
    {
        local $opt{'usev4'} = 'webv4';
        foreach my $web (sort keys %builtinweb) {
            local $opt{'webv4'} = $web;
            printf "use=webv4, webv4=$web address is %s\n", get_ipv4('webv4') // 'NOT FOUND'
                if ($web !~ "6")  ## Don't bother if web site only supports IPv6;
        }
        printf "use=webv4, webv4=%s address is %s\n", opt('webv4'), get_ipv4('webv4') // 'NOT FOUND'
            if ! exists $builtinweb{opt('webv4')};
    }
    if (opt('cmdv4')) {
        local $opt{'usev4'} = 'cmdv4';
        printf "use=cmdv4, cmdv4=%s address is %s\n", opt('cmdv4'), get_ipv4('cmdv4') // 'NOT FOUND';
    }

    # Now force IPv6
    printf "----- Test_possible_ip with 'get_ipv6' -----\n";
    printf "use=ipv6, ipv6=%s address is %s\n", opt('ipv6'), get_ipv6('ipv6') // 'NOT FOUND'
        if defined opt('ipv6');

    {
        # Note: The `ip` command adds a `@eth0` suffix to the names of VLAN
        # interfaces. That `@eth0` suffix is NOT part of the interface name.
        my @ifs = map({ /^[^\s:]*:\s*([^\s:@]+)/ ? $1 : () }
                      `command -v ip >/dev/null && ip -o link show`);
        @ifs = map({ /^([a-zA-Z].*?)(?::?\s.*)?$/ ? $1 : () }
                   `command -v ifconfig >/dev/null && ifconfig -a`) if $? || !@ifs;
        @ifs = () if $?;
        warning("failed to get list of interfaces") if !@ifs;
        foreach my $if (@ifs) {
            local $opt{'ifv6'} = $if;
            printf "use=ifv6, ifv6=%s address is %s\n", opt('ifv6'), get_ipv6('ifv6') // 'NOT FOUND';
        }
    }
    {
        local $opt{'usev6'} = 'webv6';
        foreach my $web (sort keys %builtinweb) {
            local $opt{'webv6'} = $web;
            printf "use=webv6, webv6=$web address is %s\n", get_ipv6('webv6') // 'NOT FOUND'
                if ($web !~ "4");  ## Don't bother if web site only supports IPv4
        }
        printf "use=webv6, webv6=%s address is %s\n", opt('webv6'), get_ipv6('webv6') // 'NOT FOUND'
            if ! exists $builtinweb{opt('webv6')};
    }
    if (opt('cmdv6')) {
        local $opt{'usev6'} = 'cmdv6';
        printf "use=cmdv6, cmdv6=%s address is %s\n", opt('cmdv6'), get_ipv6('cmdv6') // 'NOT FOUND';
    }

    exit 0 unless opt('debug');
}
######################################################################
## test_geturl - print (and save if -test) result of fetching a URL
######################################################################
sub test_geturl {
    my $url = shift;

    my $reply = geturl(
        proxy => opt('proxy'),
        url => $url,
        login => opt('login'),
        password => opt('password'),
    );
    print "URL $url\n";
    print $reply // "<undefined>\n";
    exit;
}
######################################################################
## load_file
######################################################################
sub load_file {
    my $file   = shift;
    my $buffer = '';

    if (exists($ENV{'TEST_CASE'})) {
        my $try = "$file-$ENV{'TEST_CASE'}";
        $file = $try if -f $try;
    }

    local *FD;
    if (open(FD, "< $file")) {
        read(FD, $buffer, -s FD);
        close(FD);
        debug("Loaded %d bytes from %s", length($buffer), $file);
    } else {
        debug("Load failed from %s (%s)", $file, $!);
    }
    return $buffer;
}
######################################################################
## save_file
######################################################################
sub save_file {
    my ($file, $buffer, $opt) = @_;

    $file .= "-$ENV{'TEST_CASE'}" if exists $ENV{'TEST_CASE'};
    if (defined $opt) {
        my $i = 0;
        while (-f "$file-$i") {
            if ('unique' =~ /^$opt/i) {
                my $a = join('\n', grep {!/^Date:/} split /\n/, $buffer);
                my $b = join('\n', grep {!/^Date:/} split /\n/, load_file("$file-$i"));
                last if $a eq $b;
            }
            $i++;
        }
        $file = "$file-$i";
    }
    debug("Saving to %s", $file);
    local *FD;
    open(FD, "> $file") or return;
    print FD $buffer;
    close(FD);
    return $buffer;
}
######################################################################
## print_opt
## print_globals
## print_config
## print_cache
## print_info
######################################################################
sub _print_hash {
    my ($string, $ptr) = @_;
    my $value = $ptr;

    if (!defined($ptr)) {
        $value = "<undefined>";
    } elsif (ref $ptr eq 'HASH') {
        foreach my $key (sort keys %$ptr) {
            if (($key eq "login") || ($key eq "password")) {
               $value = "<redacted>";
            } else {
                $value = $ptr->{$key};
            }
            _print_hash("${string}\{$key\}", $value);
        }
        return;
    }
    printf "%-36s : %s\n", $string, $value;
}
sub print_hash {
    my ($string, $hash) = @_;
    printf "=== %s ====\n", $string;
    _print_hash($string, $hash);
}
sub print_opt     { print_hash("opt",     \%opt);     }
sub print_globals { print_hash("globals", \%globals); }
sub print_config  { print_hash("config",  \%config);  }
sub print_cache   { print_hash("cache",   \%cache);   }
sub print_info {
    print_opt();
    print_globals();
    print_config();
    print_cache();
}
######################################################################
## pipecmd      - run an external command
## logger
## sendmail
######################################################################
sub pipecmd {
    my $cmd   = shift;
    my $stdin = join("\n", @_);
    my $ok    = 0;

    ## remove trailing newlines
    1 while chomp($stdin);

    ## override when debugging.
    $cmd = opt('exec') ? "| $cmd" : "> /dev/null";

    ## execute the command.
    local *FD;
    if (!open(FD, $cmd)) {
        printf STDERR "%s: cannot execute command %s.\n", $program, $cmd;

    } elsif ($stdin && (!print FD "$stdin\n")) {
        printf STDERR "%s: failed writting to %s.\n", $program, $cmd;
        close(FD);

    } elsif (!close(FD)) {
        printf STDERR "%s: failed closing %s.(%s)\n", $program, $cmd, $@;

    } elsif (opt('exec') && $?) {
        printf STDERR "%s: failed %s. (%s)\n", $program, $cmd, $@;

    } else {
        $ok = 1;
    }
    return $ok;
}
sub logger {
    if (opt('syslog') && opt('facility') && opt('priority')) {
        my $facility = opt('facility');
        my $priority = opt('priority');
        return pipecmd("logger -p$facility.$priority -t${program}\[$$\]", @_);
    }
    return 1;
}
sub sendmail {
    my $recipients = opt('mail');

    if (opt('mail-failure') && ($result ne 'OK' && $result ne '0')) {
        $recipients = opt('mail-failure');
    }
    if ($msgs && $recipients && $msgs ne $last_msgs) {
        pipecmd("sendmail -oi $recipients",
                "To: $recipients",
                "Subject: status report from $program\@$hostname",
                "\r\n",
                $msgs,
                "",
                "regards,",
                "   $program\@$hostname (version $version)"
        );
    }
    $last_msgs = $msgs;
    $msgs      = '';
}
######################################################################
##  split_by_comma
##  merge
##  default
##  minimum
##  opt
######################################################################
sub split_by_comma {
    my $string = shift;

    return split /\s*[, ]\s*/, $string if defined $string;
    return ();
}
sub merge {
    my %merged = ();
    foreach my $h (@_) {
        foreach my $k (keys %$h) {
            $merged{$k} = $h->{$k} unless exists $merged{$k};
        }
    }
    return \%merged;
}
sub default {
    my $v = shift;
    return $variables{'merged'}{$v}{'default'};
}
sub minimum {
    my $v = shift;
    return $variables{'merged'}{$v}{'minimum'};
}
sub opt {
    my $v = shift;
    my $h = shift;
    return $config{$h}{$v} if defined($h) && defined($config{$h}{$v});
    return $opt{$v} // $globals{$v} // default($v);
}
sub min {
    my $min = shift;
    foreach my $arg (@_) {
        $min = $arg if $arg < $min;
    }
    return $min;
}
sub max {
    my $max = shift;
    foreach my $arg (@_) {
        $max = $arg if $arg > $max;
    }
    return $max;
}
######################################################################
## ynu
######################################################################
sub ynu {
    my ($value, $yes, $no, $undef) = @_;

    return $no if !($value // '');
    return $yes if $value eq '1';
    foreach (qw(yes true)) {
        return $yes if $_ =~ /^$value/i;
    }
    foreach (qw(no false)) {
        return $no if $_ =~ /^$value/i;
    }
    return $undef;
}
######################################################################
## msg
## debug
## warning
## fatal
######################################################################
sub _msg {
    my $fh     = shift;
    my $log    = shift;
    my $prefix = shift;
    my $format = shift;
    my $buffer = sprintf $format, @_;
    chomp($buffer);

    $prefix = sprintf "%-9s ", $prefix if $prefix;
    if ($file) {
        $prefix .= "file $file";
        $prefix .= ", line $lineno" if $lineno;
        $prefix .= ": ";
    }
    if ($prefix) {
        $buffer = "$prefix$buffer";
        $buffer =~ s/\n/\n$prefix/g;
    }
    $buffer .= "\n";
    print $fh $buffer;

    $msgs .= $buffer if $log;
    logger($buffer) if $log;

}
sub msg     { _msg(*STDOUT, 0, '',         @_);                                   }
sub verbose { _msg(*STDOUT, 1, @_)             if opt('verbose');                 }
sub info    { _msg(*STDOUT, 1, 'INFO:',    @_) if opt('verbose');                 }
sub debug   { _msg(*STDOUT, 0, 'DEBUG:',   @_) if opt('debug');                   }
sub debug2  { _msg(*STDOUT, 0, 'DEBUG:',   @_) if opt('debug') && opt('verbose'); }
sub warning { _msg(*STDERR, 1, 'WARNING:', @_);                                   }
sub fatal   { _msg(*STDERR, 1, 'FATAL:',   @_); sendmail(); exit(1);              }
sub success { _msg(*STDOUT, 1, 'SUCCESS:', @_);                                   }
sub failed  { _msg(*STDERR, 1, 'FAILED:',  @_); $result = 'FAILED';               }
sub prettytime { return scalar(localtime(shift)); }

sub prettyinterval {
    my $interval = shift;
    use integer;
    my $s = $interval % 60; $interval /= 60;
    my $m = $interval % 60; $interval /= 60;
    my $h = $interval % 24; $interval /= 24;
    my $d = $interval;

    my $string = "";
    $string .= "$d day"    if $d;
    $string .= "s"         if $d > 1;
    $string .= ", "        if $string && $h;
    $string .= "$h hour"   if $h;
    $string .= "s"         if $h > 1;
    $string .= ", "        if $string && $m;
    $string .= "$m minute" if $m;
    $string .= "s"         if $m > 1;
    $string .= ", "        if $string && $s;
    $string .= "$s second" if $s;
    $string .= "s"         if $s > 1;
    return $string;
}
sub interval {
    my $value = shift;
    if ($value =~ /^(\d+)(seconds|s)/i) {
        $value = $1;
    } elsif ($value =~ /^(\d+)(minutes|m)/i) {
        $value = $1 * 60;
    } elsif ($value =~ /^(\d+)(hours|h)/i) {
        $value = $1 * 60*60;
    } elsif ($value =~ /^(\d+)(days|d)/i) {
        $value = $1 * 60*60*24;
    } elsif ($value !~ /^\d+$/) {
        $value = undef;
    }
    return $value;
}
sub interval_expired {
    my ($host, $time, $interval) = @_;

    return 1 if !exists $cache{$host};
    return 1 if !exists $cache{$host}{$time}      || !$cache{$host}{$time};
    return 1 if !exists $config{$host}{$interval} || !$config{$host}{$interval};

    return $now > ($cache{$host}{$time} + $config{$host}{$interval});
}



######################################################################
## check_value
######################################################################
sub check_value {
    my ($value, $def) = @_;
    my $type     = $def->{'type'};
    my $min      = $def->{'minimum'};
    my $required = $def->{'required'};

    if (!defined $value && !$required) {
        ;

    } elsif ($type eq T_DELAY) {
        $value = interval($value);
        $value = $min if defined($value) && defined($min) && $value < $min;

    } elsif ($type eq T_NUMBER) {
        return undef if $value !~ /^\d+$/;
        $value = $min if defined($min) && $value < $min;

    } elsif ($type eq T_BOOL) {
        if ($value =~ /^(y(es)?|t(rue)?|1)$/i) {
            $value = 1;
        } elsif ($value =~ /^(n(o)?|f(alse)?|0)$/i) {
            $value = 0;
        } else {
            return undef;
        }
    } elsif ($type eq T_FQDN || $type eq T_OFQDN && $value ne '') {
        $value = lc $value;
        return undef if $value !~ /[^.]\.[^.]/;

    } elsif ($type eq T_FQDNP) {
        $value = lc $value;
        return undef if $value !~ /[^.]\.[^.].*(:\d+)?$/;

    } elsif ($type eq T_PROTO) {
        $value = lc $value;
        return undef if !exists $services{$value};

    } elsif ($type eq T_USE) {
        $value = lc $value;
        return undef if !exists $ip_strategies{$value};

    } elsif ($type eq T_USEV4) {
        $value = lc $value;
        return undef if ! exists $ipv4_strategies{$value};

    } elsif ($type eq T_USEV6) {
        $value = lc $value;
        return undef if ! exists $ipv6_strategies{$value};

    } elsif ($type eq T_FILE) {
        return undef if $value eq "";

    } elsif ($type eq T_IF) {
        return undef if $value !~ /^[a-zA-Z0-9:._-]+$/;

    } elsif ($type eq T_PROG) {
        return undef if $value eq "";

    } elsif ($type eq T_LOGIN) {
        return undef if $value eq "";

    } elsif ($type eq T_IP) {
        return undef if !is_ipv4($value) && !is_ipv6($value);

    } elsif ($type eq T_IPV4) {
        return undef if !is_ipv4($value);

    } elsif ($type eq T_IPV6) {
        return undef if !is_ipv6($value);

    }
    return $value;
}
######################################################################
## encode_base64 - from MIME::Base64
######################################################################
sub encode_base64 ($;$) {
    my $res = '';
    my $eol = $_[1];
    $eol = "\n" unless defined $eol;
    pos($_[0]) = 0;  # ensure start at the beginning
    while ($_[0] =~ /(.{1,45})/gs) {
        $res .= substr(pack('u', $1), 1);
        chop($res);
    }
    $res =~ tr|` -_|AA-Za-z0-9+/|;  # `# help emacs

    # fix padding at the end
    my $padding = (3 - length($_[0]) % 3) % 3;
    $res =~ s/.{$padding}$/'=' x $padding/e if $padding;
    $res;
}

######################################################################
## load_sha1_support
######################################################################
sub load_sha1_support {
    my $why         = shift;
    my $sha1_loaded = eval { require Digest::SHA1 };
    my $sha_loaded  = eval { require Digest::SHA };
    unless ($sha1_loaded || $sha_loaded) {
        fatal("%s", <<"EOM");
Error loading the Perl module Digest::SHA1 or Digest::SHA needed for $why update.
On Debian, the package libdigest-sha1-perl or libdigest-sha-perl must be installed.
EOM
    }
    if ($sha1_loaded) {
        import Digest::SHA1 (qw/sha1_hex/);
    } elsif ($sha_loaded) {
        import Digest::SHA (qw/sha1_hex/);
    }
}
######################################################################
## load_json_support
######################################################################
sub load_json_support {
    my $why = shift;
    my $json_loaded = eval { require JSON::PP };
    unless ($json_loaded) {
        fatal("%s", <<"EOM");
Error loading the Perl module JSON::PP needed for $why update.
EOM
    }
    import JSON::PP (qw/decode_json encode_json/);
}

######################################################################
## curl_cmd() function to execute system curl command
######################################################################
sub curl_cmd {
    my @params = @_;
    my $tmpfile;
    my $tfh;
    my $system_curl = quotemeta(subst_var('@CURL@', 'curl'));
    my %curl_codes = (  ## Subset of error codes from https://curl.haxx.se/docs/manpage.html
         2 => "Failed to initialize. (Most likely a bug in ddclient, please open issue at https://github.com/ddclient/ddclient)",
         3 => "URL malformed. The syntax was not correct",
         5 => "Couldn't resolve proxy. The given proxy host could not be resolved.",
         6 => "Couldn't resolve host. The given remote host was not resolved.",
         7 => "Failed to connect to host.",
        22 => "HTTP page not retrieved. The requested url was not found or returned another error.",
        28 => "Operation timeout. The specified time-out period was reached according to the conditions.",
        35 => "SSL connect error. The SSL handshaking failed.",
        47 => "Too many redirects. When following redirects, curl hit the maximum amount.",
        52 => "The server didn't reply anything, which here is considered an error.",
        51 => "The peer's SSL certificate or SSH MD5 fingerprint was not OK.",
        58 => "Problem with the local certificate.",
        60 => "Peer certificate cannot be authenticated with known CA certificates.",
        67 => "The user name, password, or similar was not accepted and curl failed to log in.",
        77 => "Problem with reading the SSL CA cert (path? access rights?).",
        78 => "The resource referenced in the URL does not exist.",
       127 => "$system_curl was not found",
    );

    debug("CURL: %s", $system_curl);
    fatal("curl not found") if ($system_curl eq '');
    return '' if (scalar(@params) == 0); ## no parameters provided

    # Hard code to /tmp rather than use system TMPDIR to protect from malicious
    # shell instructions in TMPDIR environment variable.  All systems should have /tmp.
    $tfh = File::Temp->new(DIR => '/tmp',
                           TEMPLATE => 'ddclient_XXXXXXXXXX');
    $tmpfile = $tfh->filename;

    debug("CURL Tempfile: %s", $tmpfile);
    {
        local $\ = "\n";  ## Terminate the file,
        local $, = "\n";  ## and each parameter, with a newline.
        print($tfh @params);
    }
    close($tfh);
    my $reply = qx{ $system_curl --config $tmpfile 2>/dev/null; };
    if ((my $rc = $?>>8) != 0) {
        warning("CURL error (%d) %s", $rc, $curl_codes{$rc} // "Unknown return code. Check $system_curl is installed and its manpage.");
    }
    return $reply;
}

######################################################################
## escape_curl_param() makes sure any special characters within a
## curl parameter is properly escaped.
######################################################################
sub escape_curl_param {
    my $str = shift // '';

    return '' if ($str eq '');
    $str =~ s/\\/\\\\/g;## Escape backslashes
    $str =~ s/"/\\"/g;  ## Escape double-quotes
    $str =~ s/\n/\\n/g; ## Escape newline
    $str =~ s/\r/\\r/g; ## Escape carrage return
    $str =~ s/\t/\\t/g; ## Escape tabs
    $str =~ s/\v/\\v/g; ## Escape vertical whitespace
    return $str;
}

sub geturl {
    my %params = @_;
    my $proxy = $params{proxy};
    my $url = $params{url};
    my $login = $params{login};
    my $password = $params{password};
    my $ipversion = ($params{ipversion}) ? int($params{ipversion}) : 0;
    my $headers = $params{headers} // '';
    my $method = $params{method} // 'GET';
    my $data = $params{data} // '';

    my $reply;
    my $server;
    my $use_ssl = 0;
    my $force_ssl = 0;
    my $protocol;
    my $timeout  = opt('timeout');
    my @curlopt = ();
    my @header_lines = ();

    ## canonify proxy and url
    $force_ssl = 1 if ($url =~ /^https:/);
    $proxy  =~ s%^https?://%%i if defined($proxy);
    $url    =~ s%^https?://%%i;
    $server = $url;
    $server =~ s%[?/].*%%;
    $url    =~ s%^[^?/]*/?%%;

    $use_ssl = 1 if ($force_ssl || ($globals{'ssl'} && !($params{ignore_ssl_option} // 0)));

    $protocol = ($use_ssl ? "https" : "http");

    debug("proxy    = %s", $proxy // '<undefined>');
    debug("protocol = %s", $protocol);
    debug("server   = %s", $server);
    (my $_url = $url) =~ s%\?.*%?<redacted>%; #redact possible credentials
    debug("url      = %s", $_url);
    debug("ip ver   = %s", $ipversion);

    if (!opt('exec')) {
        debug("skipped network connection");
        verbose("SENDING:", "%s", "${server}/${url}");
    } else {
        push(@curlopt, "silent");
        push(@curlopt, "include"); ## Include HTTP response for compatibility
        push(@curlopt, "insecure") if ($use_ssl && !($params{ssl_validate} // 1));
        push(@curlopt, "cacert=\"".escape_curl_param(opt('ssl_ca_file')).'"') if defined(opt('ssl_ca_file'));
        push(@curlopt, "capath=\"".escape_curl_param(opt('ssl_ca_dir')).'"') if defined(opt('ssl_ca_dir'));
        push(@curlopt, "ipv4") if ($ipversion == 4);
        push(@curlopt, "ipv6") if ($ipversion == 6);
        push(@curlopt, "user-agent=\"".escape_curl_param("${program}/${version}").'"');
        push(@curlopt, "connect-timeout=$timeout");
        push(@curlopt, "max-time=$timeout");
        push(@curlopt, "request=$method");
        push(@curlopt, "user=\"".escape_curl_param("${login}:${password}").'"') if (defined($login) && defined($password));
        push(@curlopt, "proxy=\"".escape_curl_param("${protocol}://${proxy}").'"') if defined($proxy);
        push(@curlopt, "url=\"".escape_curl_param("${protocol}://${server}/${url}").'"');

        # Each header line is added individually
        @header_lines = split('\n', $headers);
        $_ = "header=\"".escape_curl_param($_).'"' foreach (@header_lines);
        push(@curlopt, @header_lines);

        # Add in the data if any was provided (for POST/PATCH)
        push(@curlopt, "data=\"".escape_curl_param(${data}).'"') if ($data);

        # don't include ${url} as that might expose login credentials
        $0 = sprintf("%s - Curl system cmd sending to %s", $program, "${protocol}://${server}");
        verbose("SENDING:", "Curl system cmd to %s", "${protocol}://${server}");
        verbose("SENDING:", "%s", $_) foreach (@curlopt);

        $reply = curl_cmd(@curlopt);
        verbose("RECEIVE:", "%s", $reply // "<undefined>");
        if (!$reply) {
            # don't include ${url} as that might expose login credentials
            warning("curl cannot connect to %s://%s using IPv%s",${protocol},${server},$ipversion);
        }
    }

    ## during testing simulate reading the URL
    if (opt('test')) {
        my $filename = "$server/$url";
        $filename =~ s|/|%2F|g;
        if (opt('exec')) {
            $reply = save_file("$savedir/$filename", $reply, 'unique');
        } else {
            $reply = load_file("$savedir/$filename");
        }
    }

    $reply =~ s/\r//g if defined $reply;
    return $reply;
}

######################################################################
## get_ip
######################################################################
sub get_ip {
    my $use = lc shift;
    $use    = 'disabled' if ($use eq 'no'); # backward compatibility
    my $h   = shift;
    my ($ip, $arg, $reply, $url, $skip) = (undef, opt($use, $h), '');
    $arg = '' unless $arg;

    if ($use eq 'ip') {
        $ip  = opt('ip', $h);
        if (!is_ipv4($ip) && !is_ipv6($ip)) {
            warning("'%s' is not a valid IPv4 or IPv6 address", $ip // '');
            $ip = undef;
        }
        $arg = 'ip';

    } elsif ($use eq 'if') {
        $ip = get_ip_from_interface($arg);

    } elsif ($use eq 'cmd') {
        if ($arg) {
            $skip = opt('cmd-skip', $h) // '';
            $reply = `$arg`;
            $reply = '' if $?;
        }

    } elsif ($use eq 'web') {
        $url = opt('web', $h) // '';
        $skip = opt('web-skip', $h) // '';

        if (exists $builtinweb{$url}) {
            $skip = $builtinweb{$url}->{'skip'} unless $skip;
            $url  = $builtinweb{$url}->{'url'};
        }
        $arg = $url;

        if ($url) {
            $reply = geturl(
                proxy => opt('proxy', $h),
                url => $url,
                ssl_validate => opt('web-ssl-validate', $h),
            ) // '';
        }

    } elsif (($use eq 'cisco')) {
        # Stuff added to support Cisco router ip http daemon
        # User fw-login should only have level 1 access to prevent
        # password theft.  This is pretty harmless.
        my $queryif = opt('if', $h);
        $skip = opt('fw-skip', $h) // '';

        # Convert slashes to protected value "\/"
        $queryif =~ s%\/%\\\/%g;

        # Protect special HTML characters (like '?')
        $queryif =~ s/([\?&= ])/sprintf("%%%02x", ord($1))/ge;

        $url = "http://" . opt('fw', $h) . "/level/1/exec/show/ip/interface/brief/${queryif}/CR";
        $reply = geturl(
            url => $url,
            login => opt('fw-login', $h),
            password => opt('fw-password', $h),
            ignore_ssl_option => 1,
            ssl_validate => opt('fw-ssl-validate', $h),
        ) // '';
        $arg = $url;

    } elsif (($use eq 'cisco-asa')) {
        # Stuff added to support Cisco ASA ip https daemon
        # User fw-login should only have level 1 access to prevent
        # password theft.  This is pretty harmless.
        my $queryif = opt('if', $h);
        $skip = opt('fw-skip', $h) // '';

        # Convert slashes to protected value "\/"
        $queryif =~ s%\/%\\\/%g;

        # Protect special HTML characters (like '?')
        $queryif =~ s/([\?&= ])/sprintf("%%%02x", ord($1))/ge;

        $url = "https://" . opt('fw', $h) . "/exec/show%20interface%20${queryif}";
        $reply = geturl(
            url => $url,
            login => opt('fw-login', $h),
            password => opt('fw-password', $h),
            ignore_ssl_option => 1,
            ssl_validate => opt('fw-ssl-validate', $h),
        ) // '';
        $arg = $url;

    } elsif ($use eq 'disabled') {
        ## This is a no-op... Do not get an IP address for this host/service
        $reply = '';

    } else {
        $url = opt('fw', $h) // '';
        $skip = opt('fw-skip', $h) // '';

        if (exists $builtinfw{$use}) {
            $skip = $builtinfw{$use}->{'skip'} unless $skip;
            $url  = "http://${url}" . $builtinfw{$use}->{'url'} unless $url =~ /\//;
        }
        $arg = $url;

        if ($url) {
            $reply = geturl(
                url => $url,
                login => opt('fw-login', $h),
                password => opt('fw-password', $h),
                ignore_ssl_option => 1,
                ssl_validate => opt('fw-ssl-validate', $h),
            ) // '';
        }
    }
    if (!defined $reply) {
        $reply = '';
    }
    if (($skip // '') ne '') {
        $skip  =~ s/ /\\s/is;
        $reply =~ s/^.*?${skip}//is;
    }
    $ip //= extract_ipv4($reply) // extract_ipv6($reply);
    warning("found neither IPv4 nor IPv6 address") if !defined($ip);
    if ($use ne 'ip' && ($ip // '') eq '0.0.0.0') {
        $ip = undef;
    }

    debug("get_ip: using %s, %s reports %s", $use, $arg, $ip // "<undefined>");
    return $ip;
}

######################################################################
## Regex to find IPv4 address. Accepts embedded leading zeros.
######################################################################
my $regex_ipv4 = qr/(?:(?<octet>25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?&octet)/;

######################################################################
## is_ipv4() validates if string is valid IPv4 address with no preceding
## or trailing spaces/characters, not even line breaks.
######################################################################
sub is_ipv4 {
    return (shift // '') =~ /\A$regex_ipv4\z/;
}

######################################################################
## extract_ipv4() finds the first valid IPv4 address in the given string,
## removes embedded leading zeros, and returns the result.
######################################################################
sub extract_ipv4 {
    (shift // '') =~ /(?:\b|_)($regex_ipv4)(?:\b|_)/ or return undef;
    (my $ip = $1) =~ s/\b0+\B//g; ## remove embedded leading zeros
    return $ip;
}

######################################################################
## Regex that matches an IPv6 address. Accepts embedded leading zeros.
## Accepts IPv4-mapped IPv6 addresses such as 64:ff9b::192.0.2.13.
######################################################################
my $regex_ipv6 = qr/
    # Define some named groups so we can use Perl's recursive subpattern feature for shorthand:
    (?<g>[0-9A-F]{1,4}){0}  # "g" matches a group of 1 to 4 hex chars
    (?<g_>(?&g):){0}        # "g_" matches a group of 1 to 4 hex chars followed by a colon
    (?<_g>:(?&g)){0}        # "_g" matches a colon followed by a group of 1 to 4 hex chars
    (?<g0>(?&g)?){0}        # "g0" is an optional "g" (matches a group of 0 to 4 hex chars)
    (?<g0_>(?&g0):){0}      # "g0_" is an optional "g" followed by a colon
    (?<x>[:.0-9A-Z]){0}     # "x" matches chars that should never come before or after the address
    (?<ip4>$regex_ipv4){0}  # "ip4" matches an IPv4 address x.x.x.x

    # Now for the regex itself:
    (?<!(?&x))  # Not preceded by a character that is not allowed to come before the address
    (?:
      (?&g_){7}(?&g)     # Exactly 8 groups of 1-4 hex chars
      | (?&g_){1,7}:     # OR compressed form with the double colon at the end
      | :(?&_g){1,7}     # OR compressed form with the double colon at the beginning
      | ::               # OR compressed to just a double colon
      |                  # OR compressed form with the double colon in the middle:
        (?=                   # Only consider this case if the string...
          (?&g0_){2,7}(?&g0)  # ...has 3 to 8 possibly empty groups (at least 3 because there
                              # will be at least one group before the ::, at least one group
                              # after the ::, and the :: itself is an empty group)...
          (?!(?&x))           # ...then ends.
        )                     # If the condition is true, then:
        (?&g_){1,6}           #   1 to 6 non-empty groups before the double colon
        (?&_g){1,6}           #   1 to 6 non-empty groups after the double colon
      |                  # OR an IPv4-mapped IPv6 address:
        (?:                # It starts with a 96-bit prefix represented by:
          (?&g_){6}          # Exactly 6 groups of 1-4 hex chars with their colons
          | (?&g_){1,5}:     # OR compressed form with the double colon at the end
          | ::(?&g_){0,5}    # OR compressed form with the double colon at the beginning
          |                  # OR compressed form with the double colon in the middle:
            (?=                 # Only consider this case if the prefix...
              (?&g0_){3,6}      # ...has 3 to 6 possibly empty groups...
              (?&ip4)(?!(?&x))  # ...then ends.
            )                   # If the condition is true, then:
            (?&g_){1,4}         #   1 to 4 non-empty groups before the double colon
            (?&_g){1,4}         #   1 to 4 non-empty groups after the double colon
            :                   #   colon separating the IPv6 part from the IPv4 part
        )
        (?&ip4)            # Prefix is followed by an IPv4 address
    )
    (?!(?&x))  # Not followed by a character that is not allowed to come after the address
/xi;

######################################################################
## is_ipv6() validates if string is valid IPv6 address with no preceding
## or trailing spaces/characters, not even line breaks.
######################################################################
sub is_ipv6 {
    return (shift // '') =~ /\A$regex_ipv6\z/;
}

######################################################################
## extract_ipv6() finds the first valid IPv6 address in the given string,
## removes embedded leading zeros, and returns the result.
######################################################################
sub extract_ipv6 {
    (shift // '') =~ /($regex_ipv6)/ or return undef;
    (my $ip = $1) =~ s/\b0+\B//g; ## remove embedded leading zeros
    return $ip;
}

######################################################################
## Regex that matches an IPv6 address that is probably globally routable.
## Accepts embedded leading zeros.
######################################################################
my $regex_ipv6_global = qr{
    (?!  # Is not one of the following addresses:
        0{0,4}:             # ::/16 is assumed to never contain globaly routable addresses
      | f[cd][0-9a-f]{2}:   # fc00::/7 RFC4193 ULA
      | fe[89ab][0-9a-f]:   # fe80::/10 link local
      | ff[0-9a-f]{2}:      # ff00::/8 multicast
    )
    $regex_ipv6             # And is a valid IPv6 address
}xi;

######################################################################
## is_ipv6_global() returns true if the string is a valid IPv6 address
## that is probably globally routable, with no preceding or trailing
## characters. All addresses in the ::/16 block are assumed to not be
## globally routable.
######################################################################
sub is_ipv6_global {
    return (shift // '') =~ /\A$regex_ipv6_global\z/
}

######################################################################
## extract_ipv6_global() finds the first IPv6 address in the given
## string that satisfies is_ipv6_global(), removes embedded leading
## zeros, and returns the result. Returns undef if no such address is
## found.
######################################################################
sub extract_ipv6_global {
    (shift // '') =~ /($regex_ipv6_global)/ or return undef;
    (my $ip = $1) =~ s/\b0+\B//g; ## remove embedded leading zeros
    return $ip;
}

######################################################################
## Regex that matches an IPv6 address that is unique local (ULA).
## Accepts embedded leading zeros.
######################################################################
my $regex_ipv6_ula = qr{
    (?=  # Address starts with
      f[cd][0-9a-f]{2}:     # fc00::/7 RFC4193 ULA
    )
    $regex_ipv6             # And is a valid IPv6 address
}xi;

######################################################################
## get_default_interface finds the default network interface based on
## the IP routing table on the system.  We validate that the interface
## found is likely to have global routing (e.g. is not LOOPBACK).
## Returns undef if no global scope interface can be found for IP version.
######################################################################
sub get_default_interface {
    my $ipver = int(shift // 4);    ## Defaults to IPv4 if not specified
    my $ipstr = ($ipver == 6) ? 'inet6' : 'inet';
    my $reply = shift // '';  ## Pass in data for unit testing purposes only
    my $cmd = "test";

    return undef if (($ipver != 4) && ($ipver != 6));

    if (!$reply) { ## skip if test data passed in.
        ## Best option is the ip command from iproute2 package
        $cmd = "ip -$ipver -o route list match default"; $reply = qx{ $cmd 2>/dev/null };
        ## Fallback is the netstat command. This is only option on MacOS.
        if ($?) { $cmd = "netstat -rn -$ipver";     $reply = qx{ $cmd 2>/dev/null }; } # Linux, FreeBSD
        if ($?) { $cmd = "netstat -rn -f $ipstr";   $reply = qx{ $cmd 2>/dev/null }; } # MacOS
        if ($?) { $cmd = "netstat -rn";             $reply = qx{ $cmd 2>/dev/null }; } # Busybox
        if ($?) { $cmd = "missing ip or netstat command";
            failed("Unable to obtain default route information -- %s", $cmd)
        }
    }
    debug("Reply from '%s' :\n------\n%s------", $cmd, $reply);

    # Check we have IPv6 address in case we got routing table from non-specific cmd above
    return undef if (($ipver == 6) && !extract_ipv6($reply));
    # Filter down to just the default interfaces
    my @list = split(/\n/, $reply);
    @list = grep(/^default|^(?:0\.){3}0|^::\/0/, @list); # Select 'default' or '0.0.0.0' or '::/0'
    return undef if (scalar(@list) == 0);
    debug("Default routes found for IPv%s :\n%s", $ipver, join("\n",@list));

    # now check each interface to make sure it is global (not loopback).
    foreach my $line (@list) {
        ## Interface will be after "dev" or the last word in the line. Must accept blank spaces
        ## at the end.  Interface name may not have any whitespace or forward slash.
        $line =~ /\bdev\b\s*\K[^\s\/]+|\b[^\s\/]+(?=[\s\/]*$)/;
        my $interface = $&;
        ## If test data was passed in skip following tests
        if ($cmd ne "test") {
            ## We do not want the loopback interface or anything interface without global scope
            $cmd = "ip -$ipver -o addr show dev $interface scope global"; $reply = qx{$cmd 2>/dev/null};
            if ($?) { $cmd = "ifconfig $interface";                       $reply = qx{$cmd 2>/dev/null}; }
            if ($?) { $cmd = "missing ip or ifconfig command";
                failed("Unable to obtain information for '%s' -- %s", $interface, $cmd);
            }
            debug("Reply from '%s' :\n------\n%s------", $cmd, $reply);
        }
        ## Has global scope, is not LOOPBACK
        return($interface) if (($reply) && ($reply !~ /\bLOOPBACK\b/));
    }
    return undef;
}

######################################################################
## get_ip_from_interface() finds an IPv4 or IPv6 address from a network
## interface. Defaults to IPv4 unless '6' passed as 2nd parameter.
######################################################################
sub get_ip_from_interface {
    my $interface = shift // "default";
    my $ipver = int(shift // 4);    ## Defaults to IPv4 if not specified
    my $scope = lc(shift // "gua"); ## "gua" or "ula"
    my $reply = shift // '';  ## Pass in data for unit testing purposes only
    my $MacOS = shift // 0;   ## For testing can set to 1 if input data is MacOS/FreeBSD format
    my $count = 0;
    my $cmd = "test";

    if (($ipver != 4) && ($ipver != 6)) {
        warning("get_ip_from_interface() invalid IP version: %s", $ipver);
        return undef;
    }

    if ((lc($interface) eq "default") && (!$reply)) { ## skip if test data passed in.
        $interface = get_default_interface($ipver);
        return undef if !defined($interface);
    }

    if ($ipver == 4) {
        if (!$reply) { ## skip if test data passed in.
            ## Try ip first, then ifconfig.
            $cmd = "ip -4 -o addr show dev $interface scope global"; $reply = qx{$cmd 2>/dev/null};
            if ($?) { $cmd = "ifconfig $interface";                  $reply = qx{$cmd 2>/dev/null}; }
            if ($?) { $cmd = "missing ip or ifconfig command";
                failed("Unable to obtain information for '%s' -- %s", $interface, $cmd);
            }
        }
        debug("Reply from '%s' :\n------\n%s------", $cmd, $reply);

        ## IPv4 is simple, we just need to find the first IPv4 address returned in the list.
        my @reply = split(/\n/, $reply);
        @reply = grep(/\binet\b/, @reply);  # Select only IPv4 entries
        return extract_ipv4($reply[0]);
    }

    ## From this point on we only looking for IPv6 address.
    if (($scope ne "gua") && ($scope ne "ula")) {
        warning("get_ip_from_interface() invalid IPv6 scope: %s, using type GUA", $scope);
        $scope = "gua";
    }

    $cmd = "test data";
    if (!$reply) { ## skip if test data passed in.
        ## Try ip first, then ifconfig with -L for MacOS/FreeBSD then finally ifconfig for everything else
        $cmd = "ip -6 -o addr show dev $interface scope global"; $reply = qx{$cmd 2>/dev/null};   # Linux
        if ($?) { $cmd = "ifconfig -L $interface"; $MacOS = 1;   $reply = qx{$cmd 2>/dev/null}; } # MacOS/FreeBSD
        if ($?) { $cmd = "ifconfig $interface";                  $reply = qx{$cmd 2>/dev/null}; } # Anything without iproute2 or -L
        if ($?) { $cmd = "missing ip or ifconfig command";
            failed("Unable to obtain information for '%s' -- %s", $interface, $cmd);
        }
    }
    debug("Reply from '%s' :\n------\n%s------", $cmd, $reply);

    ## IPv6 is more complex than IPv4.  Start by filtering on only "inet6" addresses
    ## Then remove deprecated or temporary addresses and finally seleect on global or local addresses
    my @reply = split(/\n/, $reply);
    @reply = grep(/\binet6\b/, @reply);                             # Select only IPv6 entries
    @reply = grep(!/\bdeprecated\b|\btemporary\b/, @reply);         # Remove deprecated and temporary
    @reply = ($scope eq "gua") ? grep(/$regex_ipv6_global/, @reply) # Select only global addresses
                               : grep(/$regex_ipv6_ula/, @reply);   #   or only ULA addresses
    debug("Raw IPv6 after filtering for %s addresses %s: (%s)\r\n%s", uc($scope), $interface, scalar(@reply), join("\n", @reply));

    ## If we filter down to zero or one result then we are done...
    return undef if (($count = scalar(@reply)) == 0);
    return extract_ipv6($reply[0]) if ($count == 1);

    ## If there are more than one we need to select the "best".
    ## First choice would be a static address.
    my @static = ($MacOS == 1) ? grep(!/^.*\bvltime\b.*$/i, @reply)              # MacOS/FreeBSD, no 'vltime'
                               : grep(/^.*\bvalid_lft.\bforever\b.*$/i, @reply); # Everything else 'forever' life
    $count = scalar(@static);
    debug("Possible Static IP addresses %s: (%s)\r\n%s", $interface, $count, join("\n", @static));

    ## If only one result then we are done.  If there are more than one static addresses
    ## then we will replace our original list with the list of statics and sort on them.
    ## If zero static addresses we fall through with our original list.
    return extract_ipv6($static[0]) if ($count == 1);
    @reply = @static if ($count > 1);

    ## Sort what we have by the prefix length, IP address "length" and finally valid life.
    my @sorted = sort {
        ## We give preference to IP addressess with the longest prefix... so we prefer a /128 over a /64
        ## this is a decimal (\d+) either after the word "prefixlen" or after a forward slash.
        (($b =~ /(?:\bprefixlen\b\s*|\/)(\d+)/i)[0] // 0) <=> (($a =~ /(?:\bprefixlen\b\s*|\/)(\d+)/i)[0] // 0)

        ## If there are multiple the same then we prefer "shorter" IP addresses in the
        ## theory that a shorter address is more likely assigned by DHCPv6 than SLAAC.
        ## E.g. 2001:db8:4341:0781::8214/64 is preferable to 2001:db8:4341:0781:34a6:c329:c52e:8ba6/64
        ## So we count the number () of groups of [0-9a-f] blocks in the IP address.
     || (()= (extract_ipv6($a) // '') =~ /[0-9A-F]+/gi) <=> (()= (extract_ipv6($b) // '') =~ /[0-9A-F]+/gi)

        ## Finally we check remaining valid lifetime and prefer longer remaining life.
        ## This is a desimal (\d+) after the word "valid_lft" or "vltime". Only available
        ## from iproute2 or MacOS/FreeBSD version of ifconfig (-L parameter).
     || (($b =~ /(?:\bvalid_lft\b\s*|\bvltime\b\s*)(\d+)/i)[0] // 0) <=> (($a =~ /(?:\bvalid_lft\b\s*|\bvltime\b\s*)(\d+)/i)[0] // 0)
    } @reply;
    debug("Sorted list of IP addresss for %s: (%s)\r\n%s", $interface, scalar(@sorted), join("\n", @sorted));

    ## Whatever sorted to the top is the best choice for IPv6 address
    return extract_ipv6($sorted[0]);
}

######################################################################
## get_ipv4
######################################################################
sub get_ipv4 {
    my $usev4 = lc(shift);  ## Method to obtain IP address
    my $h     = shift;      ## Host/service making the request

    my $ipv4  = undef;      ## Found IPv4 address
    my $reply = '';         ## Text returned from various methods
    my $url   = '';         ## URL of website or firewall
    my $skip  = '';         ## Regex of pattern to skip before looking for IP
    my $arg   = opt($usev4, $h) // '';  ## Value assigned to the "usev4" method

    if ($usev4 eq 'ipv4') {
        ## Static IPv4 address is provided in "ipv4=<address>"
        $ipv4  = $arg;
        if (!is_ipv4($ipv4)) {
            warning("'%s' is not a valid IPv4",$ipv4 // '');
            $ipv4 = undef;
        }
        $arg = 'ipv4';  # For debug message at end of function

    } elsif ($usev4 eq 'ifv4') {
        ## Obtain IPv4 address from interface mamed in "ifv4=<if>"
        warning("'if-skip' is deprecated and does nothing for IPv4") if (opt('verbose') && opt('if-skip', $h));
        $ipv4 = get_ip_from_interface($arg,4);

    } elsif ($usev4 eq 'cmdv4') {
        ## Obtain IPv4 address by executing the command in "cmdv4=<command>"
        warning("'cmd-skip' is deprecated and does nothing for IPv4") if (opt('verbose') && opt('cmd-skip', $h));
        if ($arg) {
            my $sys_cmd = quotemeta($arg);
            $reply = qx{$sys_cmd};
            $reply = '' if $?;
        }

    } elsif ($usev4 eq 'webv4') {
        ## Obtain IPv4 address by accessing website at url in "webv4=<url>"
        $url = $arg;
        $skip = opt('webv4-skip', $h) // '';
        if (exists $builtinweb{$url}) {
            $skip = $builtinweb{$url}->{'skip'} unless $skip;
            $url  = $builtinweb{$url}->{'url'};
            $arg  = $url;
        }
        if ($url) {
            $reply = geturl( proxy => opt('proxy', $h),
                url => $url,
                ipversion => 4, # when using a URL to find IPv4 address we should force use of IPv4
                ssl_validate => opt('ssl-validate', $h),
            ) // '';
        }

    } elsif ($usev4 eq 'cisco' || $usev4 eq 'cisco-asa') {
        # Stuff added to support Cisco router ip http or ASA https daemon
        # User fw-login should only have level 1 access to prevent
        # password theft.  This is pretty harmless.
        warning("'if' does nothing for IPv4. Use 'ifv4'") if (opt('if', $h));
        warning("'fw' does nothing for IPv4. Use 'fwv4'") if (opt('fw', $h));
        warning("'fw-skip' does nothing for IPv4. Use 'fwv4-skip'") if (opt('fw-skip', $h));
        my $queryif = opt('ifv4', $h) // opt('if', $h);
        $skip = opt('fwv4-skip', $h) // opt('fw-skip', $h) // '';
        # Convert slashes to protected value "\/"
        $queryif =~ s%\/%\\\/%g;
        # Protect special HTML characters (like '?')
        $queryif =~ s/([\?&= ])/sprintf("%%%02x", ord($1))/ge;
        if ($usev4 eq 'cisco') {
            $url = "http://" . (opt('fwv4', $h) // opt('fw', $h)) . "/level/1/exec/show/ip/interface/brief/${queryif}/CR";
        } else {
            $url = "https://" . (opt('fwv4', $h) // opt('fw', $h))  . "/exec/show%20interface%20${queryif}";
        }
        $arg = $url;
        $reply = geturl(
            url => $url,
            login => opt('fw-login', $h),
            password => opt('fw-password', $h),
            ipversion => 4, # when using a URL to find IPv4 address we should force use of IPv4
            ignore_ssl_option => 1,
            ssl_validate => opt('ssl-validate', $h),
        ) // '';

    } elsif ($usev4 eq 'disabled') {
        ## This is a no-op... Do not get an IPv4 address for this host/service
        $reply = '';

    } else {
        warning("'fw' does nothing for IPv4. Use 'fwv4'") if (opt('fw', $h));
        warning("'fw-skip' does nothing for IPv4. Use 'fwv4-skip'") if (opt('fw-skip', $h));
        $url  = opt('fwv4', $h) // opt('fw', $h) // '';
        $skip = opt('fwv4-skip', $h) // opt('fw-skip', $h) // '';

        if (exists $builtinfw{$usev4}) {
            $skip = $builtinfw{$usev4}->{'skip'} unless $skip;
            $url  = "http://${url}" . $builtinfw{$usev4}->{'url'} unless $url =~ /\//;
        }
        $arg = $url;
        if ($url) {
            $reply = geturl(
                url => $url,
                login => opt('fw-login', $h),
                password => opt('fw-password', $h),
                ipversion => 4, # when using a URL to find IPv4 address we should force use of IPv4
                ignore_ssl_option => 1,
                ssl_validate => opt('ssl-validate', $h),
            ) // '';
        }
    }

    ## Set to loopback address if no text set yet
    $reply = '0.0.0.0' if !defined($reply);
    if (($skip // '') ne '') {
        $skip  =~ s/ /\\s/is;
        $reply =~ s/^.*?${skip}//is;
    }
    ## If $ipv4 not set yet look for IPv4 address in the $reply text
    $ipv4 //= extract_ipv4($reply);
    ## Return undef for loopback address unless statically assigned by "ipv4=0.0.0.0"
    $ipv4 = undef if (($usev4 ne 'ipv4') && (($ipv4 // '') eq '0.0.0.0'));
    debug("get_ipv4: using (%s, %s) reports %s", $usev4, $arg, $ipv4 // "<undefined>");
    return $ipv4;
}

######################################################################
## get_ipv6
######################################################################
sub get_ipv6 {
    my $usev6 = lc(shift);  ## Method to obtain IP address
    $usev6    = 'disabled' if ($usev6 eq 'no'); # backward compatibility
    my $h     = shift;      ## Host/service making the request

    my $ipv6  = undef;      ## Found IPv6 address
    my $reply = '';         ## Text returned from various methods
    my $url   = '';         ## URL of website or firewall
    my $skip  = '';         ## Regex of pattern to skip before looking for IP
    my $arg   = opt($usev6, $h) // '';  ## Value assigned to the "usev6" method

    if ($usev6 eq 'ipv6' || $usev6 eq 'ip') {
        ## Static IPv6 address is provided in "ipv6=<address>"
        if ($usev6 eq 'ip') {
            warning("'usev6=ip' is deprecated. Use 'usev6=ipv6'");
            $usev6 = 'ipv6';
            ## If there is a value for ipv6= use that, else use value for ip=
            $arg = opt($usev6, $h) // $arg;
        }
        $ipv6 = $arg;
        if (!is_ipv6($ipv6)) {
            warning("'%s' is not a valid IPv6",$ipv6 // '');
            $ipv6 = undef;
        }
        $arg = 'ipv6';  # For debug message at end of function

    } elsif ($usev6 eq 'ifv6' || $usev6 eq 'if' ) {
        ## Obtain IPv6 address from interface mamed in "ifv6=<if>"
        if ($usev6 eq 'if') {
            warning("'usev6=if' is deprecated. Use 'usev6=ifv6'");
            $usev6 = 'ifv6';
            ## If there is a value for ifv6= use that, else use value for if=
            $arg = opt($usev6, $h) // $arg;
        }
        warning("'if-skip' is deprecated and does nothing for IPv6") if (opt('verbose') && opt('if-skip', $h));
        $ipv6 = get_ip_from_interface($arg,6);

    }  elsif ($usev6 eq 'cmdv6' || $usev6 eq 'cmd') {
        ## Obtain IPv6 address by executing the command in "cmdv6=<command>"
        if ($usev6 eq 'cmd') {
            warning("'usev6=cmd' is deprecated. Use 'usev6=cmdv6'");
            $usev6 = 'cmdv6';
            ## If there is a value for cmdv6= use that, else use value for cmd=
            $arg = opt($usev6, $h) // $arg;
        }
        warning("'cmd-skip' is deprecated and does nothing for IPv6") if (opt('verbose') && opt('cmd-skip', $h));
        if ($arg) {
            my $sys_cmd = quotemeta($arg);
            $reply = qx{$sys_cmd};
            $reply = '' if $?;
        }

    } elsif ($usev6 eq 'webv6' || $usev6 eq 'web') {
        ## Obtain IPv6 address by accessing website at url in "webv6=<url>"
        if ($usev6 eq 'web') {
            warning("'usev6=web' is deprecated. Use 'usev6=webv6'");
            $usev6 = 'webv6';
            ## If there is a value for webv6= use that, else use value for web=
            $arg = opt($usev6, $h) // $arg;
        }
        warning("'web-skip' does nothing for IPv6. Use 'webv6-skip'") if (opt('web-skip', $h));
        $url = $arg;
        $skip = opt('webv6-skip', $h) // '';
        if (exists $builtinweb{$url}) {
            $skip = $builtinweb{$url}->{'skip'} unless $skip;
            $url  = $builtinweb{$url}->{'url'};
            $arg  = $url;
        }
        if ($url) {
            $reply = geturl(
                proxy => opt('proxy'),
                url => $url,
                ipversion => 6, # when using a URL to find IPv6 address we should force use of IPv6
                ssl_validate => opt('ssl-validate', $h),
            ) // '';
        }

    } elsif ($usev6 eq 'cisco' || $usev6 eq 'cisco-asa') {
        warning("'usev6=cisco' and 'usev6=cisco-asa' are not implemented and do nothing");
        $reply = '';

    } elsif ($usev6 eq 'disabled') {
        ## This is a no-op... Do not get an IPv6 address for this host/service
        warning("'usev6=no' is deprecated. Use 'usev6=disabled'") if ($usev6 eq 'no');
        $reply = '';

    } else {
        warning("'usev6=%s' is not implemented and does nothing", $usev6);
        $reply = '';

    }

    ## Set to loopback address if no text set yet
    $reply = '::' if !defined($reply);
    if (($skip // '') ne '') {
        $skip  =~ s/ /\\s/is;
        $reply =~ s/^.*?${skip}//is;
    }
    ## If $ipv6 not set yet look for IPv6 address in the $reply text
    $ipv6 //= extract_ipv6($reply);
    ## Return undef for loopback address unless statically assigned by "ipv6=::"
    $ipv6 = undef if (($usev6 ne 'ipv6') && (($ipv6 // '') eq '::'));
    debug("get_ipv6: using (%s, %s) reports %s", $usev6, $arg, $ipv6 // "<undefined>");
    return $ipv6;
}

######################################################################
## group_hosts_by
######################################################################
sub group_hosts_by {
##TODO - Update for wantipv4 and wantipv6
    my ($hosts, $attributes) = @_;
    my %attrs = (map({ ($_ => 1) } @$attributes), 'wantip' => 1);
    my @attrs = sort(keys(%attrs));
    my %groups = ();
    foreach my $h (@$hosts) {
        my $sig = join(',', map({ sprintf("%s=%s", $_, $config{$h}{$_} // '') } @attrs));
        push @{$groups{$sig}}, $h;
    }
    return %groups;
}

######################################################################
## encode_www_form_urlencoded
######################################################################
sub encode_www_form_urlencoded {
    my $formdata = shift;

    my $must_encode = qr'[<>"#%{}|\\^~\[\]`;/?:=&+]';
    my $encoded;
    my $i = 0;
    foreach my $k (keys %$formdata) {
        my $kenc = $k;
        my $venc = $formdata->{$k};

        $kenc =~ s/($must_encode)/sprintf('%%%02X', ord($1))/ge;
        $venc =~ s/($must_encode)/sprintf('%%%02X', ord($1))/ge;

        $kenc =~ s/ /+/g;
        $venc =~ s/ /+/g;

        $encoded .= $kenc . '=' . $venc;
        if ($i < (keys %$formdata) - 1) {
            $encoded .= '&';
        }
        $i++;
    }

    return $encoded;
}

######################################################################
## nic_examples
######################################################################
sub nic_examples {
    my $examples  = "";
    my $separator = "";
    foreach my $s (sort keys %services) {
        my $subr = $services{$s}{'examples'};
        my $example;

        if (defined($subr) && ($example = &$subr())) {
            chomp($example);
            $examples .= $example;
            $examples .= "\n\n$separator";
            $separator = "\n";
        }
    }
    my $intro = <<"EoEXAMPLE";
== CONFIGURING ${program}

The configuration file, ${program}.conf, can be used to define the
default behaviour and operation of ${program}.  The file consists of
sequences of global variable definitions and host definitions.

Global definitions look like:
  name=value [,name=value]*

For example:
  daemon=5m
  use=if, if=eth0
  proxy=proxy.myisp.com
  protocol=dyndns2

specifies that ${program} should operate as a daemon, checking the
eth0 interface for an IP address change every 5 minutes and use the
'dyndns2' protocol by default. The daemon interval can be specified
as seconds (600s), minutes (5m), hours (1h) or days (1d).

Host definitions look like:
  [name=value [,name=value]*]* a.host.domain [,b.host.domain] [login] [password]

For example:
  protocol=noip, \\
  login=your-username, password=your-password  myhost.noip.com
  login=your-username, password=your-password  myhost.noip.com,myhost2.noip.com

specifies two host definitions.

The first definition will use the noip protocol,
your-username and your-password to update the ip-address of
myhost.noip.com and my2ndhost.noip.com.

The second host definition will use the current default protocol
('dyndns2'), my-login and my-password to update the ip-address of
myhost.dyndns.org and my2ndhost.dyndns.org.

The order of this sequence is significant because the values of any
global variable definitions are bound to a host definition when the
host definition is encountered.

See the sample-${program}.conf file for further examples.
EoEXAMPLE
    $intro .= "\n== NIC specific variables and examples:\n$examples" if $examples;
    return $intro;
}
######################################################################
## nic_updateable
## Returns true if we can go ahead and update the IP address at server
######################################################################
sub nic_updateable {
    my $host   = shift;
    my $sub    = shift;
    my $update = 0;
    my $ip     = $config{$host}{'wantip'};
    my $ipv4   = $config{$host}{'wantipv4'};
    my $ipv6   = $config{$host}{'wantipv6'};
    my $use    = opt('use',   $host) // 'disabled';
    my $usev4  = opt('usev4', $host) // 'disabled';
    my $usev6  = opt('usev6', $host) // 'disabled';
    $use       = 'disabled' if ($use eq 'no');   # backward compatibility
    $usev6     = 'disabled' if ($usev6 eq 'no'); # backward compatibility
    $use       = 'disabled' if ($usev4 ne 'disabled') || ($usev6 ne 'disabled');

    # If we have a valid IP address and we have previously warned that it was invalid.
    # reset the warning count back to zero.
    if (($use ne 'disabled') && $ip && $warned_ip{$host}) {
        $warned_ip{$host} = 0;
        warning("IP address for %s valid: %s. Reset warning count", $host, $ip);
    }
    if (($usev4 ne 'disabled') && $ipv4 && $warned_ipv4{$host}) {
        $warned_ipv4{$host} = 0;
        warning("IPv4 address for %s valid: %s. Reset warning count", $host, $ipv4);
    }
    if (($usev6 ne 'disabled') && $ipv6 && $warned_ipv6{$host}) {
        $warned_ipv6{$host} = 0;
        warning("IPv6 address for %s valid: %s. Reset warning count", $host, $ipv6);
    }

    if ($config{$host}{'login'} eq '') {
        warning("null login name specified for host %s.", $host);

    } elsif ($config{$host}{'password'} eq '') {
        warning("null password specified for host %s.", $host);

    } elsif ($opt{'force'}) {
        info("forcing update of %s.", $host);
        $update = 1;

    } elsif (!exists($cache{$host})) {
        info("forcing updating %s because no cached entry exists.", $host);
        $update = 1;

    } elsif ($cache{$host}{'wtime'} && $cache{$host}{'wtime'} > $now) {
        warning("cannot update %s from %s to %s until after %s.",
                $host,
                ($cache{$host}{'ip'} ? $cache{$host}{'ip'} : '<nothing>'), $ip,
                prettytime($cache{$host}{'wtime'})
        );

    } elsif ($cache{$host}{'mtime'} && interval_expired($host, 'mtime', 'max-interval')) {
        warning("forcing update of %s from %s to %s; %s since last update on %s.",
                $host,
                ($cache{$host}{'ip'} ? $cache{$host}{'ip'} : '<nothing>'), $ip,
                prettyinterval($config{$host}{'max-interval'}),
                prettytime($cache{$host}{'mtime'})
        );
        $update = 1;

    } elsif ( ($use ne 'disabled')
           && ((!exists($cache{$host}{'ip'})) || ("$cache{$host}{'ip'}" ne "$ip"))) {
        ## Check whether to update IP address for the "use" method"
        if (($cache{$host}{'status'} eq 'good') &&
            !interval_expired($host, 'mtime', 'min-interval')) {

            warning("skipping update of %s from %s to %s.\nlast updated %s.\nWait at least %s between update attempts.",
                    $host,
                    ($cache{$host}{'ip'}    ? $cache{$host}{'ip'}                : '<nothing>'),
                    $ip,
                    ($cache{$host}{'mtime'} ? prettytime($cache{$host}{'mtime'}) : '<never>'),
                    prettyinterval($config{$host}{'min-interval'})
            )
                if opt('verbose') || !($cache{$host}{'warned-min-interval'} // 0);

            $cache{$host}{'warned-min-interval'} = $now;

        } elsif (($cache{$host}{'status'} ne 'good') &&
            !interval_expired($host, 'atime', 'min-error-interval')) {

            if ( opt('verbose')
                 || ( ! $cache{$host}{'warned-min-error-interval'}
                     && (($warned_ip{$host} // 0) < $inv_ip_warn_count)) ) {

                warning("skipping update of %s from %s to %s.\nlast updated %s but last attempt on %s failed.\nWait at least %s between update attempts.",
                        $host,
                        ($cache{$host}{'ip'}    ? $cache{$host}{'ip'}                : '<nothing>'),
                        $ip,
                        ($cache{$host}{'mtime'} ? prettytime($cache{$host}{'mtime'}) : '<never>'),
                        ($cache{$host}{'atime'} ? prettytime($cache{$host}{'atime'}) : '<never>'),
                        prettyinterval($config{$host}{'min-error-interval'})
                );
                if (!$ip && !opt('verbose')) {
                    $warned_ip{$host} = ($warned_ip{$host} // 0) + 1;
                    warning("IP address for %s undefined. Warned %s times, suppressing further warnings", $host, $inv_ip_warn_count)
                        if ($warned_ip{$host} >= $inv_ip_warn_count);
                }
            }

            $cache{$host}{'warned-min-error-interval'} = $now;

        } else {
            $update = 1;
        }

    } elsif ( ($usev4 ne 'disabled')
           && ((!exists($cache{$host}{'ipv4'})) || ("$cache{$host}{'ipv4'}" ne "$ipv4"))) {
        ## Check whether to update IPv4 address for the "usev4" method"
        if (($cache{$host}{'status-ipv4'} eq 'good') &&
            !interval_expired($host, 'mtime', 'min-interval')) {

            warning("skipping update of %s from %s to %s.\nlast updated %s.\nWait at least %s between update attempts.",
                    $host,
                    ($cache{$host}{'ipv4'}  ? $cache{$host}{'ipv4'}              : '<nothing>'),
                    $ipv4,
                    ($cache{$host}{'mtime'} ? prettytime($cache{$host}{'mtime'}) : '<never>'),
                    prettyinterval($config{$host}{'min-interval'})
            )
                if opt('verbose') || !($cache{$host}{'warned-min-interval'} // 0);

            $cache{$host}{'warned-min-interval'} = $now;

        } elsif (($cache{$host}{'status-ipv4'} ne 'good') &&
            !interval_expired($host, 'atime', 'min-error-interval')) {

            if ( opt('verbose')
                 || ( ! $cache{$host}{'warned-min-error-interval'}
                     && (($warned_ipv4{$host} // 0) < $inv_ip_warn_count)) ) {

                warning("skipping update of %s from %s to %s.\nlast updated %s but last attempt on %s failed.\nWait at least %s between update attempts.",
                        $host,
                        ($cache{$host}{'ipv4'}  ? $cache{$host}{'ipv4'}              : '<nothing>'),
                        $ipv4,
                        ($cache{$host}{'mtime'} ? prettytime($cache{$host}{'mtime'}) : '<never>'),
                        ($cache{$host}{'atime'} ? prettytime($cache{$host}{'atime'}) : '<never>'),
                        prettyinterval($config{$host}{'min-error-interval'})
                );
                if (!$ipv4 && !opt('verbose')) {
                    $warned_ipv4{$host} = ($warned_ipv4{$host} // 0) + 1;
                    warning("IPv4 address for %s undefined. Warned %s times, suppressing further warnings", $host, $inv_ip_warn_count)
                        if ($warned_ipv4{$host} >= $inv_ip_warn_count);
                }
            }

            $cache{$host}{'warned-min-error-interval'} = $now;

        } else {
            $update = 1;
        }

    } elsif ( ($usev6 ne 'disabled')
           && ((!exists($cache{$host}{'ipv6'})) || ("$cache{$host}{'ipv6'}" ne "$ipv6"))) {
        ## Check whether to update IPv6 address for the "usev6" method"
        if (($cache{$host}{'status-ipv6'} eq 'good') &&
            !interval_expired($host, 'mtime', 'min-interval')) {

            warning("skipping update of %s from %s to %s.\nlast updated %s.\nWait at least %s between update attempts.",
                    $host,
                    ($cache{$host}{'ipv6'}  ? $cache{$host}{'ipv6'}              : '<nothing>'),
                    $ipv6,
                    ($cache{$host}{'mtime'} ? prettytime($cache{$host}{'mtime'}) : '<never>'),
                    prettyinterval($config{$host}{'min-interval'})
            )
                if opt('verbose') || !($cache{$host}{'warned-min-interval'} // 0);

            $cache{$host}{'warned-min-interval'} = $now;

        } elsif (($cache{$host}{'status-ipv6'} ne 'good') &&
            !interval_expired($host, 'atime', 'min-error-interval')) {

            if ( opt('verbose')
                 || ( ! $cache{$host}{'warned-min-error-interval'}
                     && (($warned_ipv6{$host} // 0) < $inv_ip_warn_count)) ) {

                warning("skipping update of %s from %s to %s.\nlast updated %s but last attempt on %s failed.\nWait at least %s between update attempts.",
                        $host,
                        ($cache{$host}{'ipv6'}  ? $cache{$host}{'ipv6'}              : '<nothing>'),
                        $ipv6,
                        ($cache{$host}{'mtime'} ? prettytime($cache{$host}{'mtime'}) : '<never>'),
                        ($cache{$host}{'atime'} ? prettytime($cache{$host}{'atime'}) : '<never>'),
                        prettyinterval($config{$host}{'min-error-interval'})
                );
                if (!$ipv6 && !opt('verbose')) {
                    $warned_ipv6{$host} = ($warned_ipv6{$host} // 0) + 1;
                    warning("IPv6 address for %s undefined. Warned %s times, suppressing further warnings", $host, $inv_ip_warn_count)
                        if ($warned_ipv6{$host} >= $inv_ip_warn_count);
                }
            }

            $cache{$host}{'warned-min-error-interval'} = $now;

        } else {
            $update = 1;
        }

    } elsif (defined($sub) && &$sub($host)) {
        $update = 1;
    } elsif ((defined($cache{$host}{'static'}) && defined($config{$host}{'static'}) &&
              ($cache{$host}{'static'} ne $config{$host}{'static'})) ||
             (defined($cache{$host}{'wildcard'}) && defined($config{$host}{'wildcard'}) &&
              ($cache{$host}{'wildcard'} ne $config{$host}{'wildcard'})) ||
             (defined($cache{$host}{'mx'}) && defined($config{$host}{'mx'}) &&
              ($cache{$host}{'mx'} ne $config{$host}{'mx'})) ||
             (defined($cache{$host}{'backupmx'}) && defined($config{$host}{'backupmx'}) &&
              ($cache{$host}{'backupmx'} ne $config{$host}{'backupmx'}))) {
        info("updating %s because host settings have been changed.", $host);
        $update = 1;

    } else {
        if (opt('verbose')) {
            if ($use ne 'disabled') {
                success("%s: skipped: IP address was already set to %s.", $host, $ip);
            }
            if ($usev4 ne 'disabled') {
                success("%s: skipped: IPv4 address was already set to %s.", $host, $ipv4);
            }
            if ($usev6 ne 'disabled') {
                success("%s: skipped: IPv6 address was already set to %s.", $host, $ipv6);
            }
        }
    }

    $config{$host}{'status'} = $cache{$host}{'status'} // '';
    $config{$host}{'status-ipv4'} = $cache{$host}{'status-ipv4'} // '';
    $config{$host}{'status-ipv6'} = $cache{$host}{'status-ipv6'} // '';
    $config{$host}{'update'} = $update;
    if ($update) {
        $config{$host}{'status'}                    = 'noconnect';
        $config{$host}{'status-ipv4'}               = 'noconnect';
        $config{$host}{'status-ipv6'}               = 'noconnect';
        $config{$host}{'atime'}                     = $now;
        $config{$host}{'wtime'}                     = 0;
        $config{$host}{'warned-min-interval'}       = 0;
        $config{$host}{'warned-min-error-interval'} = 0;

        delete $cache{$host}{'warned-min-interval'};
        delete $cache{$host}{'warned-min-error-interval'};
    }

    return $update;
}

######################################################################
## header_ok
######################################################################
sub header_ok {
    my ($host, $line) = @_;
    my $ok = 0;

    if ($line =~ m%^s*HTTP/.*\s+(\d+)%i) {
        my $result = $1;

        if ($result =~ m/^2\d\d$/) {
            $ok = 1;

        } elsif ($result eq '401') {
            failed("updating %s: authentication failed (%s)", $host, $line);
        } elsif ($result eq '403') {
            failed("updating %s: not authorized (%s)", $host, $line);
        }

    } else {
        failed("updating %s: unexpected line (%s)", $host, $line);
    }
    return $ok;
}

######################################################################
## DDNS providers
#  A DDNS provider consists of an example function, the update
#  function, and an optional updateable function.
#
#  The example function simply returns a string for the help message,
#  explaining how to configure the provider
#
#  The update function performs the actual record update.
#  It receives an array of hosts as its argument.
#
#  The updateable function allows a provider implementation to force
#  an update even if ddclient has itself determined no update is
#  necessary. The function shall return 1 if an update should be
#  performed, else 0.
######################################################################


######################################################################
## nic_dyndns1_examples
######################################################################
sub nic_dyndns1_examples {
    return <<"EoEXAMPLE";
o 'dyndns1'

The 'dyndns1' protocol is a deprecated protocol used by the free dynamic
DNS service offered by www.dyndns.org. The 'dyndns2' should be used to
update the www.dyndns.org service.  However, other services are also
using this protocol so support is still provided by ${program}.

Configuration variables applicable to the 'dyndns1' protocol are:
  protocol=dyndns1             ##
  server=fqdn.of.service       ## defaults to members.dyndns.org
  backupmx=no|yes              ## indicates that this host is the primary MX for the domain.
  mx=any.host.domain           ## a host MX'ing for this host definition.
  wildcard=no|yes              ## add a DNS wildcard CNAME record that points to {host}
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=dyndns1,                                         \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password                           \\
  myhost.dyndns.org

  ## multiple host update with wildcard'ing mx, and backupmx
  protocol=dyndns1,                                         \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password,                          \\
  mx=a.host.willing.to.mx.for.me,backupmx=yes,wildcard=yes  \\
  myhost.dyndns.org,my2ndhost.dyndns.org
EoEXAMPLE
}
######################################################################
## nic_dyndns1_update
######################################################################
sub nic_dyndns1_update {
    debug("\nnic_dyndns1_update -------------------");
    ## update each configured host
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        my $url;
        $url  = "https://$config{$h}{'server'}/nic/";
        $url .= ynu($config{$h}{'static'}, 'statdns', 'dyndns', 'dyndns');
        $url .= "?action=edit&started=1&hostname=YES&host_id=$h";
        $url .= "&myip=";
        $url .= $ip            if $ip;
        $url .= "&wildcard=ON" if ynu($config{$h}{'wildcard'}, 1, 0, 0);
        if ($config{$h}{'mx'}) {
            $url .= "&mx=$config{$h}{'mx'}";
            $url .= "&backmx=" . ynu($config{$h}{'backupmx'}, 'YES', 'NO');
        }

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        ) // '';
        if ($reply eq '') {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        my ($title, $return_code, $error_code) = ('', '', '');
        foreach my $line (@reply) {
            $title       = $1 if $line =~ m%<TITLE>\s*(.*)\s*</TITLE>%i;
            $return_code = $1 if $line =~ m%^return\s+code\s*:\s*(.*)\s*$%i;
            $error_code  = $1 if $line =~ m%^error\s+code\s*:\s*(.*)\s*$%i;
        }

        if ($return_code ne 'NOERROR' || $error_code ne 'NOERROR' || !$title) {
            $config{$h}{'status'} = 'failed';
            $title = "incomplete response from $config{$h}{server}" unless $title;
            warning("SENT:    %s", $url) unless opt('verbose');
            warning("REPLIED: %s", $reply);
            failed("updating %s: %s", $h, $title);

        } else {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: %s: IP address set to %s (%s)", $h, $return_code, $ip, $title);
        }
    }
}
######################################################################
## nic_dyndns2_updateable
######################################################################
sub nic_dyndns2_updateable {
    my $host   = shift;
    my $update = 0;

    if ($config{$host}{'mx'} ne $cache{$host}{'mx'}) {
        info("forcing updating %s because 'mx' has changed to %s.", $host, $config{$host}{'mx'});
        $update = 1;

    } elsif ($config{$host}{'mx'} && (ynu($config{$host}{'backupmx'}, 1, 2, 3) ne ynu($config{$host}{'backupmx'}, 1, 2, 3))) {
        info("forcing updating %s because 'backupmx' has changed to %s.", $host, ynu($config{$host}{'backupmx'}, "YES", "NO", "NO"));
        $update = 1;

    } elsif ($config{$host}{'static'} ne $cache{$host}{'static'}) {

        info("forcing updating %s because 'static' has changed to %s.", $host, ynu($config{$host}{'static'}, "YES", "NO", "NO"));
        $update = 1;

    }
    return $update;
}
######################################################################
## nic_dyndns2_examples
######################################################################
sub nic_dyndns2_examples {
    return <<"EoEXAMPLE";
o 'dyndns2'

The 'dyndns2' protocol is a newer low-bandwidth protocol used by a
free dynamic DNS service offered by www.dyndns.org.  It supports
features of the older 'dyndns1' in addition to others.  [These will be
supported in a future version of ${program}.]

Configuration variables applicable to the 'dyndns2' protocol are:
  protocol=dyndns2             ##
  server=fqdn.of.service       ## defaults to members.dyndns.org
  script=/path/to/script       ## defaults to /nic/update
  backupmx=no|yes              ## indicates that this host is the primary MX for the domain.
  static=no|yes                ## indicates that this host has a static IP address.
  custom=no|yes                ## indicates that this host is a 'custom' top-level domain name.
  mx=any.host.domain           ## a host MX'ing for this host definition.
  wildcard=no|yes              ## add a DNS wildcard CNAME record that points to {host}
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=dyndns2,                                         \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password                           \\
  myhost.dyndns.org

  ## multiple host update with wildcard'ing mx, and backupmx
  protocol=dyndns2,                                         \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password,                          \\
  mx=a.host.willing.to.mx.for.me,backupmx=yes,wildcard=yes  \\
  myhost.dyndns.org,my2ndhost.dyndns.org

  ## multiple host update to the custom DNS service
  protocol=dyndns2,                                         \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password                           \\
  my-toplevel-domain.com,my-other-domain.com
EoEXAMPLE
}
######################################################################
## nic_dyndns2_update
######################################################################
sub nic_dyndns2_update {
    debug("\nnic_dyndns2_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(login password server static custom wildcard mx backupmx) ]);

    my %errors = (
       'badauth'  => 'Bad authorization (username or password)',
       'badsys'   => 'The system parameter given was not valid',

       'notfqdn'  => 'A Fully-Qualified Domain Name was not provided',
       'nohost'   => 'The hostname specified does not exist in the database',
       '!yours'   => 'The hostname specified exists, but not under the username currently being used',
       '!donator' => 'The offline setting was set, when the user is not a donator',
       '!active'  => 'The hostname specified is in a Custom DNS domain which has not yet been activated.',
       'abuse',   => 'The hostname specified is blocked for abuse; you should receive an email notification ' .
                     'which provides an unblock request link.  More info can be found on ' .
                     'https://www.dyndns.com/support/abuse.html',

       'numhost'  => 'System error: Too many or too few hosts found. Contact support@dyndns.org',
       'dnserr'   => 'System error: DNS error encountered. Contact support@dyndns.org',

       'nochg'    => 'No update required; unnecessary attempts to change to the current address are considered abusive',
    );

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};
        my $hosts = join(',', @hosts);
        my $h     = $hosts[0];
        my $ipv4  = $config{$h}{'wantipv4'};
        my $ipv6  = $config{$h}{'wantipv6'};
        delete $config{$_}{'wantipv4'} foreach @hosts;
        delete $config{$_}{'wantipv6'} foreach @hosts;

        info("setting IPv4 address to %s for %s", $ipv4, $hosts) if $ipv4;
        info("setting IPv6 address to %s for %s", $ipv6, $hosts) if $ipv6;
        verbose("UPDATE:", "updating %s", $hosts);

        ## Select the DynDNS system to update
        my $url = "http://$config{$h}{'server'}$config{$h}{'script'}?system=";
        if ($config{$h}{'custom'}) {
            warning("updating %s: 'custom' and 'static' may not be used together. ('static' ignored)", $hosts)
                if $config{$h}{'static'};
            $url .= 'custom';

        } elsif ($config{$h}{'static'}) {
            $url .= 'statdns';

        } else {
            $url .= 'dyndns';
        }

        $url .= "&hostname=$hosts";
        $url .= "&myip=";
        $url .= $ipv4 if $ipv4;
        if ($ipv6) {
            $url .= "," if $ipv4;
            $url .= $ipv6;
        }

        ## some args are not valid for a custom domain.
        $url .= "&wildcard=ON" if ynu($config{$h}{'wildcard'}, 1, 0, 0);
        if ($config{$h}{'mx'}) {
            $url .= "&mx=$config{$h}{'mx'}";
            $url .= "&backmx=" . ynu($config{$h}{'backupmx'}, 'YES', 'NO');
        }

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        ) // '';
        if ($reply eq '') {
            failed("updating %s: Could not connect to %s.", $hosts, $config{$h}{'server'});
            next;
        }
        next if !header_ok($hosts, $reply);

        my @reply      = split /\n/, $reply;
        my $state      = 'header';

        foreach my $line (@reply) {
            if ($state eq 'header') {
                $state = 'body';

            } elsif ($state eq 'body') {
                $state = 'results' if $line eq '';

            } elsif ($state =~ /^results/) {
                $state = 'results2';

                # bug #10: some dyndns providers does not return the IP so
                # we can't use the returned IP
                my ($status, $returnedips) = split / /, lc $line;

                foreach my $h (@hosts) {
                    $config{$h}{'status'} = $status;
                    $config{$h}{'status-ipv4'} = $status if $ipv4;
                    $config{$h}{'status-ipv6'} = $status if $ipv6;
                }

                if ($status eq 'good') {
                    foreach my $h (@hosts) {
                        $config{$h}{'ipv4'}  = $ipv4 if $ipv4;
                        $config{$h}{'ipv6'}  = $ipv6 if $ipv6;
                        $config{$h}{'mtime'} = $now;
                    }

                    success("updating %s: %s: IPv4 address set to %s", $hosts, $status, $ipv4) if $ipv4;
                    success("updating %s: %s: IPv6 address set to %s", $hosts, $status, $ipv6) if $ipv6;

                } elsif (exists $errors{$status}) {
                    if ($status eq 'nochg') {
                        warning("updating %s: %s: %s", $hosts, $status, $errors{$status});

                        foreach my $h (@hosts) {
                            $config{$h}{'ipv4'}  = $ipv4 if $ipv4;
                            $config{$h}{'ipv6'}  = $ipv6 if $ipv6;
                            $config{$h}{'mtime'}  = $now;
                            $config{$h}{'status'} = 'good';
                            $config{$h}{'status-ipv4'} = 'good' if $ipv4;
                            $config{$h}{'status-ipv6'} = 'good' if $ipv6;
                        }

                    } else {
                        failed("updating %s: %s: %s", $hosts, $status, $errors{$status});
                    }

                } elsif ($status =~ /w(\d+)(.)/) {
                    my ($wait, $units) = ($1, lc $2);
                    my ($sec,  $scale) = ($wait, 1);

                    ($scale, $units) = (1, 'seconds')   if $units eq 's';
                    ($scale, $units) = (60, 'minutes')  if $units eq 'm';
                    ($scale, $units) = (60*60, 'hours') if $units eq 'h';

                    $sec = $wait * $scale;
                    foreach my $h (@hosts) {
                        $config{$h}{'wtime'} = $now + $sec;
                    }

                    warning("updating %s: %s: wait %s %s before further updates", $hosts, $status, $wait, $units);

                } else {
                    failed("updating %s: unexpected status (%s)", $hosts, $line);
                }
            }
        }
        failed("updating %s: Could not connect to %s.", $hosts, $config{$h}{'server'})
            if $state ne 'results2';
    }
}

######################################################################
## nic_dnsexit2_examples
######################################################################
sub nic_dnsexit2_examples {
    return <<"EoEXAMPLE";
o 'dnsexit2'

The 'dnsexit2' protocol is the updated protocol for the (free) dynamic hostname services
of 'DNSExit' (www.dnsexit.com). Their API is accepting JSON payload.

Configuration variables applicable to the 'dnsexit2' protocol are:
  protocol=dnsexit2         ##
  password=YourAPIKey       ## API Key of your account.
  server=api.dnsexit.com    ## defaults to api.dnsexit.com.
  path=/dns/                ## defaults to /dns/.
  ttl=5                     ## defaults to 5 minutes.
  zone=''                   ## defaults to empty, which assumes the zone is equal to the fully.qualified.host (is root of your DNSExit domain).
  fully.qualified.host      ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=dnsexit2
  password=YourAPIKey
  yourown.publicvm.com

  ## two hosts (which must be) on the same zone
  protocol=dnsexit2
  password=YourAPIKey
  zone=yourown.publicvm.com
  host1.yourown.publicvm.com,host2.yourown.publicvm.com

EoEXAMPLE
}
######################################################################
## nic_dnsexit2_update
##
## by @jortkoopmans
## based on https://dnsexit.com/dns/dns-api/
##
######################################################################
sub nic_dnsexit2_update {
    debug("\nnic_dnsexit2_update -------------------");

    ## Update each configured host (hosts cannot be grouped on this API)
    foreach my $h (@_) {
        # All the known status
        my %status = (
             '0'        => [ 'good',    'Success! Actions got executed successfully.' ],
             '1'        => [ 'warning', 'Some execution problems. May not indicate actions failures. Some action may got executed fine and some may have problems.' ],
             '2'        => [ 'badauth', 'API Key Authentication Error. The API Key is missing or wrong.' ],
             '3'        => [ 'error',   'Missing Required Definitions. Your JSON file may missing some required definitions.' ],
             '4'        => [ 'error',   'JSON Data Syntax Error. Your JSON file has syntax error.' ],
             '5'        => [ 'error',   'JSON Defined Record Type not Supported. Your JSON may try to update some record type not supported by our system.' ],
             '6'        => [ 'error',   'System Error. Our system problem. May not be your problem. Contact our support if you got such error.' ],
             '7'        => [ 'error',   'Error getting post data. Our server has problem to receive your JSON posting.' ],
        );
        my $ipv4 = delete $config{$h}{'wantipv4'};
        my $ipv6 = delete $config{$h}{'wantipv6'};
       
        # Updates for ipv4 and ipv6 need to be combined in a single API call, create Hash of Arrays for tracking
        my %total_payload;

        foreach my $ip ($ipv4, $ipv6){
            next if (!$ip);
            my $ipv  = ($ip eq ($ipv6 // '')) ? '6' : '4';
            my $type = ($ip eq ($ipv6 // '')) ? 'AAAA' : 'A';

            info("Going to update IPv$ipv address to %s for %s.", $ip, $h);
            $config{$h}{'status-ipv$ipv'} = 'failed';

            # One key per ipv (4 or 6)
            my %payload = (name => $h, type => $type, content => $ip, ttl => $config{$h}{'ttl'});
            @total_payload{$ipv} = \%payload;
        };
        # Set the URL of the API endpoint
        my $url = "https://$config{$h}{'server'}$config{$h}{'path'}";

        # Set additional headers
        my $header = "Content-Type: application/json\nAccept: application/json";

        # Set the zone if empty
        if ( not defined $config{$h}{'zone'}){
            debug("Zone not defined, setting to default hostname: %s", $h);
            $config{$h}{'zone'} = $h
        } else {
            debug("Zone is: %s", $config{$h}{'zone'});
        }

        # Build total JSON payload
        my @payload_values = values %total_payload;
        my $data = encode_json({
            apikey => $config{$h}{'password'},
            domain => $config{$h}{'zone'},
            update => \@payload_values
        });

        # Make the call
        my $reply = geturl(
            proxy     => opt('proxy'),
            url       => $url,
            headers   => $header,
            method    => 'POST',
            data      => $data
        );

        # No reply, declare as failed
        unless ($reply && header_ok($h, $reply)){
            failed("updating %s: Could not connect to %s%s.", $h, $config{$h}{'server'}, $config{$h}{'path'});
            last;
        };

        # Reply found
        debug("%s", $reply);
        # Extract the HTTP response code
        (my $http_status) = ($reply =~ m%^s*HTTP/.*\s+(\d+)%i);
        debug("HTTP response code: %s", $http_status);

        # If not 200, bail
        if ( $http_status ne '200' ){
            failed("Failed to update Host\n%s", $h);
            failed("HTTP response code\n%s", $http_status);
            failed("Full reply\n%s", $reply) unless opt('verbose');
            next;
        }

        # Strip HTTP response headers
        (my $strip_status) = ($reply =~ s/^[\s\S]*?(?=\{"code":)//);
        debug("strip_status");
        debug("%s", $strip_status);
        if ($strip_status) {
            debug("HTTP headers are stripped.");
        }
        else {
            warning("Unexpected: no HTTP headers stripped!");
        }

        # Decode the remaining reply, it should be JSON.
        my $response = decode_json($reply);

        # It should at least have a 'code' and 'message'.
        if (defined($response->{'code'}) and defined($response->{'message'})) {
            if (exists $status{$response->{'code'}}) {
                # Add the server response data to the applicable array
                push( @{ $status {$response->{'code'} } }, $response->{'message'});
                if (defined($response->{'details'})) {
                    push ( @{ $status {$response->{'code'} } }, $response->{'details'}[0]);
                } else {
                    # Keep it symmetrical for simplicity
                    push ( @{ $status {$response->{'code'} } }, "no details received");
                }

                # Set data from array
                my ($status, $message, $srv_message, $srv_details) = @{ $status {$response->{'code'} } };
                info("Status: %s -- Message: %s", $status, $message);
                info("Server Message: %s -- Server Details: %s", $srv_message, $srv_details);
                $config{$h}{'status'} = $status;

                # Handle statuses
                if ($status eq 'good') {
                    $config{$h}{'mtime'}  = $now;
                    my $tracked_ipv;
                    foreach $tracked_ipv ( keys %total_payload ){
                        $config{$h}{"ipv$tracked_ipv"} = $total_payload{$tracked_ipv}{content};
                        $config{$h}{"status-ipv$tracked_ipv"} = 'good';
                        success("%s", $message);
                        success("Updated %s successfully to IPv$tracked_ipv address %s at time %s", $h, $total_payload{$tracked_ipv}{content}, prettytime($config{$h}{'mtime'}));
                    }
                } elsif ($status eq 'warning') {
                    warning("%s", $message);
                    warning("Server response: %s", $srv_message);
                } elsif ($status =~ m'^(badauth|error)$') {
                    failed("%s", $message);
                    failed("Server response: %s", $srv_message);
                } else {
                    failed("This should not be possible");
                }
            } else {
                failed("Status code %s is unknown!", $response->{'code'});
            }
        } else {
            failed("Did not receive expected \"code\" and \"message\" keys in server response.");
            failed("Response:");
            failed("%s", $response);
        }
    }
}
######################################################################
## nic_noip_update
## Note: uses same features as nic_dyndns2_update, less return codes
######################################################################
sub nic_noip_update {
    debug("\nnic_noip_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(login password server static custom wildcard mx backupmx) ]);

    my %errors = (
        'badauth'  => 'Invalid username or password',
        'badagent' => 'Invalid user agent',
        'nohost'   => 'The hostname specified does not exist in the database',
        '!donator' => 'The offline setting was set, when the user is not a donator',
        'abuse',   => 'The hostname specified is blocked for abuse; open a trouble ticket at https://www.no-ip.com',
        'numhost'  => 'System error: Too many or too few hosts found. open a trouble ticket at https://www.no-ip.com',
        'dnserr'   => 'System error: DNS error encountered. Contact support@dyndns.org',
        'nochg'    => 'No update required; unnecessary attempts to change to the current address are considered abusive',
    );

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};
        my $hosts = join(',', @hosts);
        my $h     = $hosts[0];
        my $ip    = $config{$h}{'wantip'};
        delete $config{$_}{'wantip'} foreach @hosts;

        info("setting IP address to %s for %s", $ip, $hosts);
        verbose("UPDATE:", "updating %s", $hosts);

        my $url = "https://$config{$h}{'server'}/nic/update?system=noip&hostname=$hosts&myip=";
        $url .= $ip if $ip;

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        ) // '';
        if ($reply eq '') {
            failed("updating %s: Could not connect to %s.", $hosts, $config{$h}{'server'});
            next;
        }
        next if !header_ok($hosts, $reply);

        my @reply = split /\n/, $reply;
        my $state = 'header';
        foreach my $line (@reply) {
            if ($state eq 'header') {
                $state = 'body';

            } elsif ($state eq 'body') {
                $state = 'results' if $line eq '';

            } elsif ($state =~ /^results/) {
                $state = 'results2';

                my ($status, $ip) = split / /, lc $line;
                my $h = shift @hosts;

                $config{$h}{'status'} = $status;
                if ($status eq 'good') {
                    $config{$h}{'ip'}     = $ip;
                    $config{$h}{'mtime'}  = $now;
                    success("updating %s: %s: IP address set to %s", $h, $status, $ip);

                } elsif (exists $errors{$status}) {
                    if ($status eq 'nochg') {
                        warning("updating %s: %s: %s", $h, $status, $errors{$status});
                        $config{$h}{'ip'}     = $ip;
                        $config{$h}{'mtime'}  = $now;
                        $config{$h}{'status'} = 'good';

                    } else {
                        failed("updating %s: %s: %s", $h, $status, $errors{$status});
                    }

                } elsif ($status =~ /w(\d+)(.)/) {
                    my ($wait, $units) = ($1, lc $2);
                    my ($sec,  $scale) = ($wait, 1);

                    ($scale, $units) = (1, 'seconds')   if $units eq 's';
                    ($scale, $units) = (60, 'minutes')  if $units eq 'm';
                    ($scale, $units) = (60*60, 'hours') if $units eq 'h';

                    $sec = $wait * $scale;
                    $config{$h}{'wtime'} = $now + $sec;
                    warning("updating %s: %s: wait %s %s before further updates", $h, $status, $wait, $units);

                } else {
                    failed("updating %s: unexpected status (%s)", $h, $line);
                }
            }
        }
        failed("updating %s: Could not connect to %s.", $hosts, $config{$h}{'server'})
            if $state ne 'results2';
    }
}
######################################################################
## nic_noip_examples
######################################################################
sub nic_noip_examples {
    return <<"EoEXAMPLE";
o 'noip'

The 'No-IP Compatible' protocol is used to make dynamic dns updates
over an http request.  Details of the protocol are outlined at:
https://www.noip.com/integrate/

Configuration variables applicable to the 'noip' protocol are:
  protocol=noip                ##
  server=fqdn.of.service       ## defaults to dynupdate.no-ip.com
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=noip,                                   \\
  login=userlogin\@domain.com,                     \\
  password=noip-password                           \\
  myhost.no-ip.biz


EoEXAMPLE
}
######################################################################
## nic_dslreports1_examples
######################################################################
sub nic_dslreports1_examples {
    return <<"EoEXAMPLE";
o 'dslreports1'

The 'dslreports1' protocol is used by a free DSL monitoring service
offered by www.dslreports.com.

Configuration variables applicable to the 'dslreports1' protocol are:
  protocol=dslreports1         ##
  server=fqdn.of.service       ## defaults to www.dslreports.com
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  unique-number                ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=dslreports1,                                     \\
  login=my-dslreports-login,                                \\
  password=my-dslreports-password                           \\
  123456

Note: DSL Reports uses a unique number as the host name.  This number
can be found on the Monitor Control web page.
EoEXAMPLE
}
######################################################################
## nic_dslreports1_update
######################################################################
sub nic_dslreports1_update {
    debug("\nnic_dslreports1_update -------------------");
    ## update each configured host
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        my $url;
        $url  = "https://$config{$h}{'server'}/nic/";
        $url .= ynu($config{$h}{'static'}, 'statdns', 'dyndns', 'dyndns');
        $url .= "?action=edit&started=1&hostname=YES&host_id=$h";
        $url .= "&myip=";
        $url .= $ip if $ip;

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        ) // '';
        if ($reply eq '') {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }

        my @reply = split /\n/, $reply;
        my $return_code = '';
        foreach my $line (@reply) {
            $return_code = $1 if $line =~ m%^return\s+code\s*:\s*(.*)\s*$%i;
        }

        if ($return_code !~ /NOERROR/) {
            $config{$h}{'status'} = 'failed';
            warning("SENT:    %s", $url) unless opt('verbose');
            warning("REPLIED: %s", $reply);
            failed("updating %s", $h);

        } else {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: %s: IP address set to %s", $h, $return_code, $ip);
        }
    }
}

######################################################################
## nic_domeneshop_examples
######################################################################
sub nic_domeneshop_examples {
    return <<"EoEXAMPLE";
o 'domeneshop'

API is documented here: https://api.domeneshop.no/docs/

To generate credentials, visit https://www.domeneshop.no/admin?view=api after logging in to the control panel at
https://www.domeneshop.no/admin?view=api

Configuration variables applicable to the 'domeneshop' api are:
  protocol=domeneshop          ##
  login=token                  ## api-token
  password=secret              ## api-secret
    domain.example.com         ## the host registered with the service.             ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=domeneshop
  login=username
  password=your-password
  my.example.com

EoEXAMPLE
}

######################################################################
## nic_domeneshop_update
######################################################################
sub nic_domeneshop_update {
    debug("\nnic_domeneshop_update -------------------");

    my $endpointPath = "/v0/dyndns/update";

    ## update each configured host
    ## should improve to update in one pass
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("Setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "Updating %s", $h);

        # Set the URL that we're going to to update
        my $url;
        $url  = $globals{'ssl'} ? "https://" : "http://";
        $url .= "$config{$h}{'server'}$endpointPath?hostname=$h&myip=$ip";

        # Try to get URL
        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        );

        # No response, declare as failed
        if (!defined($reply) || !$reply) {
            failed("Updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        # evaluate response
        my @reply = split /\n/, $reply;
        my $status = shift(@reply);
        my $message = pop(@reply);
        if ($status =~ /204/) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            failed("updating %s: Server said: '%s' '%s'", $h, $status, $message);
        }
    }
}


######################################################################
## nic_zoneedit1_examples
######################################################################
sub nic_zoneedit1_examples {
    return <<"EoEXAMPLE";
o 'zoneedit1'

The 'zoneedit1' protocol is used by a DNS service offered by
www.zoneedit.com.

Configuration variables applicable to the 'zoneedit1' protocol are:
  protocol=zoneedit1           ##
  server=fqdn.of.service       ## defaults to www.zoneedit.com
  zone=zone-where-domains-are  ## only needed if 1 or more subdomains are deeper
                               ## than 1 level in relation to  the zone where it
                               ## is defined. For example, b.foo.com in a zone
                               ## foo.com doesn't need this, but a.b.foo.com in
                               ## the same zone needs zone=foo.com
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  your.domain.name             ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=zoneedit1,                                     \\
  server=dynamic.zoneedit.com,                            \\
  zone=zone-where-domains-are,                            \\
  login=my-zoneedit-login,                                \\
  password=my-zoneedit-password                           \\
  my.domain.name
EoEXAMPLE
}

######################################################################
## nic_zoneedit1_updateable
######################################################################
sub nic_zoneedit1_updateable {
    return 0;
}

######################################################################
## nic_zoneedit1_update
# <SUCCESS CODE="200" TEXT="Update succeeded." ZONE="trialdomain.com" IP="127.0.0.12">
# <SUCCESS CODE="201" TEXT="No records need updating." ZONE="bannedware.com">
# <ERROR CODE="701" TEXT="Zone is not set up in this account." ZONE="bad.com">
######################################################################
sub nic_zoneedit1_update {
    debug("\nnic_zoneedit1_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(login password server zone) ]);

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};
        my $hosts = join(',', @hosts);
        my $h     = $hosts[0];
        my $ip    = $config{$h}{'wantip'};
        delete $config{$_}{'wantip'} foreach @hosts;

        info("setting IP address to %s for %s", $ip, $hosts);
        verbose("UPDATE:", "updating %s", $hosts);

        my $url = '';
        $url .= "https://$config{$h}{'server'}/auth/dynamic.html";
        $url .= "?host=$hosts";
        $url .= "&dnsto=$ip"   if $ip;
        $url .= "&zone=$config{$h}{'zone'}" if defined $config{$h}{'zone'};

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        ) // '';
        if ($reply eq '') {
            failed("updating %s: Could not connect to %s.", $hosts, $config{$h}{'server'});
            next;
        }
        next if !header_ok($hosts, $reply);

        my @reply = split /\n/, $reply;
        foreach my $line (@reply) {
            if ($h && $line =~ /^[^<]*<(SUCCESS|ERROR)\s+([^>]+)>(.*)/) {
                my ($status, $assignments, $rest) = ($1, $2, $3);
                my ($left, %var) = parse_assignments($assignments);

                if (keys %var) {
                    my ($status_code, $status_text, $status_ip) = ('999', '', $ip);
                    $status_code = $var{'CODE'} if exists $var{'CODE'};
                    $status_text = $var{'TEXT'} if exists $var{'TEXT'};
                    $status_ip   = $var{'IP'}   if exists $var{'IP'};

                    if ($status eq 'SUCCESS' || ($status eq 'ERROR' && $var{'CODE'} eq '707')) {
                        $config{$h}{'ip'}     = $status_ip;
                        $config{$h}{'mtime'}  = $now;
                        $config{$h}{'status'} = 'good';

                        success("updating %s: IP address set to %s (%s: %s)", $h, $ip, $status_code, $status_text);

                    } else {
                        $config{$h}{'status'} = 'failed';
                        failed("updating %s: %s: %s", $h, $status_code, $status_text);
                    }
                    shift @hosts;
                    $h     = $hosts[0];
                    $hosts = join(',', @hosts);
                }
                $line = $rest;
                redo if $line;
            }
        }
        failed("updating %s: no response from %s", $hosts, $config{$h}{'server'})
            if @hosts;
    }
}
######################################################################
## nic_easydns_updateable
######################################################################
sub nic_easydns_updateable {
    my $host   = shift;
    my $update = 0;

    if ($config{$host}{'mx'} ne $cache{$host}{'mx'}) {
        info("forcing updating %s because 'mx' has changed to %s.", $host, $config{$host}{'mx'});
        $update = 1;

    } elsif ($config{$host}{'mx'} && (ynu($config{$host}{'backupmx'}, 1, 2, 3) ne ynu($config{$host}{'backupmx'}, 1, 2, 3))) {
        info("forcing updating %s because 'backupmx' has changed to %s.", $host, ynu($config{$host}{'backupmx'}, "YES", "NO", "NO"));
        $update = 1;

    } elsif ($config{$host}{'static'} ne $cache{$host}{'static'}) {

        info("forcing updating %s because 'static' has changed to %s.", $host, ynu($config{$host}{'static'}, "YES", "NO", "NO"));
        $update = 1;

    }
    return $update;
}
######################################################################
## nic_easydns_examples
######################################################################
sub nic_easydns_examples {
    return <<"EoEXAMPLE";
o 'easydns'

The 'easydns' protocol is used by the for fee DNS service offered
by www.easydns.com.

Configuration variables applicable to the 'easydns' protocol are:
  protocol=easydns             ##
  server=fqdn.of.service       ## defaults to members.easydns.com
  backupmx=no|yes              ## indicates that EasyDNS should be the secondary MX
                               ## for this domain or host.
  mx=any.host.domain           ## a host MX'ing for this host or domain.
  wildcard=no|yes              ## add a DNS wildcard CNAME record that points to {host}
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=easydns,                                         \\
  login=my-easydns.com-login,                               \\
  password=my-easydns.com-password                          \\
  myhost.easydns.com

  ## multiple host update with wildcard'ing mx, and backupmx
  protocol=easydns,                                         \\
  login=my-easydns.com-login,                               \\
  password=my-easydns.com-password,                         \\
  mx=a.host.willing.to.mx.for.me,                           \\
  backupmx=yes,                                             \\
  wildcard=yes                                              \\
  my-toplevel-domain.com,my-other-domain.com

  ## multiple host update to the custom DNS service
  protocol=easydns,                                         \\
  login=my-easydns.com-login,                               \\
  password=my-easydns.com-password                          \\
  my-toplevel-domain.com,my-other-domain.com
EoEXAMPLE
}
######################################################################
## nic_easydns_update
######################################################################
sub nic_easydns_update {
    debug("\nnic_easydns_update -------------------");

    ## each host is in a group by itself
    my %groups = map { $_ => [ $_ ] } @_;

    my %errors = (
        'NOACCESS'  => 'Authentication failed. This happens if the username/password OR host or domain are wrong.',
        'NOSERVICE' => 'Dynamic DNS is not turned on for this domain.',
        'ILLEGAL'   => 'Client sent data that is not allowed in a dynamic DNS update.',
        'TOOSOON'   => 'Update frequency is too short.',
    );

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};
        my $hosts = join(',', @hosts);
        my $h     = $hosts[0];
        my $ipv4  = $config{$h}{'wantipv4'};
        my $ipv6  = $config{$h}{'wantipv6'};
        delete $config{$_}{'wantipv4'} foreach @hosts;
        delete $config{$_}{'wantipv6'} foreach @hosts;

        info("setting IP address to %s %s for %s", $ipv4, $ipv6, $hosts);
        verbose("UPDATE:", "updating %s", $hosts);

        #'https://api.cp.easydns.com/dyn/generic.php?hostname=test.burry.ca&myip=10.20.30.40&wildcard=ON'

        my $url;
        $url  = "https://$config{$h}{'server'}$config{$h}{'script'}?";
        $url .= "hostname=$hosts";
        $url .= "&myip=";
        $url .= $ipv4 if $ipv4;
        foreach my $ipv6a ($ipv6) {
            $url .= "&myip=";
            $url .= $ipv6a
        }
        $url .= "&wildcard=" . ynu($config{$h}{'wildcard'}, 'ON', 'OFF', 'OFF') if defined $config{$h}{'wildcard'};

        if ($config{$h}{'mx'}) {
            $url .= "&mx=$config{$h}{'mx'}";
            $url .= "&backmx=" . ynu($config{$h}{'backupmx'}, 'YES', 'NO');
        }

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        ) // '';
        if ($reply eq '') {
            failed("updating %s: Could not connect to %s.", $hosts, $config{$h}{'server'});
            next;
        }
        next if !header_ok($hosts, $reply);

        my @reply = split /\n/, $reply;
        my $state = 'header';
        foreach my $line (@reply) {
            if ($state eq 'header') {
                $state = 'body';

            } elsif ($state eq 'body') {
                $state = 'results' if $line eq '';

            } elsif ($state =~ /^results/) {
                $state = 'results2';

                my ($status) = $line =~ /^(\S*)\b.*/;
                my $h = shift @hosts;

                $config{$h}{'status-ipv4'} = $status if $ipv4;
                $config{$h}{'status-ipv6'} = $status if $ipv6;
                if ($status eq 'NOERROR') {
                    $config{$h}{'ipv4'}  = $ipv4;
                    $config{$h}{'ipv6'}  = $ipv6;
                    $config{$h}{'mtime'} = $now;
                    success("updating %s: %s: IP address set to %s %s", $h, $status, $ipv4, $ipv6);

                } elsif ($status =~ /TOOSOON/) {
                    ## make sure we wait at least a little
                    my ($wait, $units) = (5, 'm');
                    my ($sec,  $scale) = ($wait, 1);

                    ($scale, $units) = (1, 'seconds')   if $units eq 's';
                    ($scale, $units) = (60, 'minutes')  if $units eq 'm';
                    ($scale, $units) = (60*60, 'hours') if $units eq 'h';
                    $config{$h}{'wtime'} = $now + $sec;
                    warning("updating %s: %s: wait %d %s before further updates", $h, $status, $wait, $units);

                } elsif (exists $errors{$status}) {
                    failed("updating %s: %s: %s", $h, $line, $errors{$status});

                } else {
                    failed("updating %s: unexpected status (%s)", $h, $line);
                }
                last;
            }
        }
        failed("updating %s: Could not connect to %s.", $hosts, $config{$h}{'server'})
            if $state ne 'results2';
    }
}
######################################################################

######################################################################
## nic_namecheap_examples
######################################################################
sub nic_namecheap_examples {
    return <<"EoEXAMPLE";

o 'namecheap'

The 'namecheap' protocol is used by DNS service offered by www.namecheap.com.

Configuration variables applicable to the 'namecheap' protocol are:
  protocol=namecheap           ##
  server=fqdn.of.service       ## defaults to dynamicdns.park-your-domain.com
  login=service-login          ## the domain of the dynamic DNS record you want to update
  password=service-password    ## Generated password for your dynamic DNS record
  hostname                     ## the subdomain to update, use @ for base domain name, * for catch all

Example ${program}.conf file entries:
  ## single host update
  protocol=namecheap                                          \\
  login=example.com                                           \\
  password=example.com-generated-password                     \\
  @

EoEXAMPLE
}
######################################################################
## nic_namecheap_update
##
## written by Dan Boardman
##
## based on https://www.namecheap.com/support/knowledgebase/
## article.aspx/29/11/how-to-use-the-browser-to-dynamically-update-hosts-ip
## needs this url to update:
## https://dynamicdns.park-your-domain.com/update?host=host_name&
## domain=domain.com&password=domain_password[&ip=your_ip]
##
######################################################################
sub nic_namecheap_update {


    debug("\nnic_namecheap1_update -------------------");

    ## update each configured host
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        my $url;
        $url = "https://$config{$h}{'server'}/update";
        my $domain = $config{$h}{'login'};
        my $host   = $h;
        $host =~ s/(.*)\.$domain(.*)/$1$2/;
        $url .= "?host=$host";
        $url .= "&domain=$domain";
        $url .= "&password=$config{$h}{'password'}";
        $url .= "&ip=";
        $url .= $ip if $ip;

        my $reply = geturl(proxy => opt('proxy'), url => $url) // '';
        if ($reply eq '') {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        if (grep /<ErrCount>0/i, @reply) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            warning("SENT:    %s", $url) unless opt('verbose');
            warning("REPLIED: %s", $reply);
            failed("updating %s: Invalid reply.", $h);
        }
    }
}

######################################################################

######################################################################
## nic_nfsn_examples
######################################################################
sub nic_nfsn_examples {
    return <<"EoEXAMPLE";

o 'nfsn'

The 'nfsn' protocol is used for the DNS service offered by www.nearlyfreespeech.net. Use this URL to get your API-Key-password:
  https://members.nearlyfreespeech.net/support/assist?tag=apikey

Configuration variables applicable to the 'nfsn' protocol are:
  protocol=nfsn
  server=api-server    ## defaults to api.nearlyfreespeech.net
  login=member-login   ## NearlyFreeSpeech.net login name
  password=api-key     ## NearlyFreeSpeech.net API key
  zone=zone            ## The DNS zone under which the hostname falls; e.g. example.com
  hostname             ## the hostname to update in the specified zone; e.g. example.com or www.example.com

Example ${program}.conf file entries:
  ## update two hosts (example.com and www.example.com) in example.com zone
  protocol=nfsn,                                         \\
  login=my-nfsn-member-login,                            \\
  password=my-nfsn-api-key,                              \\
  zone=example.com                                       \\
  example.com,www.example.com

  ## repeat the above for other zones, e.g. example.net:
  [...]
  zone=example.net                                       \\
  subdomain1.example.net,subdomain2.example.net

EoEXAMPLE
}

######################################################################
## nic_nfsn_gen_auth_header
######################################################################
sub nic_nfsn_gen_auth_header {
    my $h    = shift;
    my $path = shift;
    my $body = shift // '';

    ## API requests must include a custom HTTP header in the
    ## following format:
    ##
    ## X-NFSN-Authentication: login;timestamp;salt;hash
    ##
    ## In this header, login is the member login name of the user
    ## making the API request.
    my $auth_header = 'X-NFSN-Authentication: ';
    $auth_header .= $config{$h}{'login'} . ';';

    ## timestamp is the standard 32-bit unsigned Unix timestamp
    ## value.
    my $timestamp = time();
    $auth_header .= $timestamp . ';';

    ## salt is a randomly generated 16 character alphanumeric value
    ## (a-z, A-Z, 0-9).
    my @chars = ('A'..'Z', 'a'..'z', '0'..'9');
    my $salt;
    for (my $i = 0; $i < 16; $i++) {
        $salt .= $chars[int(rand(@chars))];
    }
    $auth_header .= $salt . ';';

    ## hash is a SHA1 hash of a string in the following format:
    ## login;timestamp;salt;api-key;request-uri;body-hash
    my $hash_string = $config{$h}{'login'} . ';' .
              $timestamp . ';' .
              $salt . ';' .
              $config{$h}{'password'} . ';';

    ## The request-uri value is the path portion of the requested URL
    ## (i.e. excluding the protocol and hostname).
    $hash_string .= $path . ';';

    ## The body-hash is the SHA1 hash of the request body (if any).
    ## If there is no request body, the SHA1 hash of the empty string
    ## must be used.
    my $body_hash = sha1_hex($body);
    $hash_string .= $body_hash;

    my $hash = sha1_hex($hash_string);
    $auth_header .= $hash;
    $auth_header .= "\n";

    return $auth_header;
}

######################################################################
## nic_nfsn_make_request
######################################################################
sub nic_nfsn_make_request {
    my $h = shift;
    my $path = shift;
    my $method = shift // 'GET';
    my $body = shift // '';

    my $base_url = "https://$config{$h}{'server'}";
    my $url      = $base_url . $path;
    my $header   = nic_nfsn_gen_auth_header($h, $path, $body);
    if ($method eq 'POST' && $body ne '') {
        $header .= "Content-Type: application/x-www-form-urlencoded\n";
    }

    return geturl(
        proxy => opt('proxy'),
        url => $url,
        headers => $header,
        method => $method,
        data => $body,
    );
}

######################################################################
## nic_nfsn_handle_error
######################################################################
sub nic_nfsn_handle_error {
    my $resp = shift;
    my $h    = shift;

    $resp =~ s/^.*?\n\n//s;  # Strip header
    my $json = eval { decode_json($resp) };
    if ($@ || ref($json) ne 'HASH' || not defined $json->{'error'}) {
        failed("Invalid error response: %s", $resp);
        return;
    }

    failed("%s", $json->{'error'});
    if (defined $json->{'debug'}) {
        failed("%s", $json->{'debug'});
    }
}

######################################################################
## nic_nfsn_update
##
## Written by John Brooks
##
## Based on API docs: https://members.nearlyfreespeech.net/wiki/API/Introduction
## Uses the API endpoints under https://api.nearlyfreespeech.net/dns/$zone/
##
## NB: There is no "updateRR" API function; to update an existing RR, we use
##     removeRR to delete the RR, and then addRR to re-add it with the new data.
##
######################################################################
sub nic_nfsn_update {
    debug("\nnic_nfsn_update -------------------");

    ## update each configured host
    foreach my $h (@_) {
        my $zone = $config{$h}{'zone'};
        my $name;

        if ($h eq $zone) {
            $name = '';
        } elsif ($h !~ /$zone$/) {
            $config{$h}{'status'} = 'failed';
            failed("updating %s: %s is outside zone %s", $h, $h, $zone);
            next;
        } else {
            $name = $h;
            $name =~ s/(.*)\.${zone}$/$1/;
        }

        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE", "updating %s", $h);

        my $list_path = "/dns/$zone/listRRs";
        my $list_body = encode_www_form_urlencoded({name => $name, type => 'A'});
        my $list_resp = nic_nfsn_make_request($h, $list_path, 'POST', $list_body);
        if (!header_ok($h, $list_resp)) {
            $config{$h}{'status'} = 'failed';
            nic_nfsn_handle_error($list_resp, $h);
            next;
        }

        $list_resp =~ s/^.*?\n\n//s;  # Strip header
        my $list = eval { decode_json($list_resp) };
        if ($@) {
            $config{$h}{'status'} = 'failed';
            failed("updating %s: JSON decoding failure", $h);
            next;
        }

        my $rr_ttl = $config{$h}{'ttl'};

        if (ref($list) eq 'ARRAY' && defined $list->[0]->{'data'}) {
            my $rr_data = $list->[0]->{'data'};
            my $rm_path = "/dns/$zone/removeRR";
            my $rm_data = {name => $name,
                           type => 'A',
                           data => $rr_data};
            my $rm_body = encode_www_form_urlencoded($rm_data);
            my $rm_resp = nic_nfsn_make_request($h, $rm_path,
                                                'POST', $rm_body);
            if (!header_ok($h, $rm_resp)) {
                $config{$h}{'status'} = 'failed';
                nic_nfsn_handle_error($rm_resp);
                next;
            }
        }

        my $add_path = "/dns/$zone/addRR";
        my $add_data = {name => $name,
                        type => 'A',
                        data => $ip,
                        ttl => $rr_ttl};
        my $add_body = encode_www_form_urlencoded($add_data);
        my $add_resp = nic_nfsn_make_request($h, $add_path, 'POST',
                                             $add_body);
        if (header_ok($h, $add_resp)) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            nic_nfsn_handle_error($add_resp, $h);
        }
    }
}

######################################################################

######################################################################
## nic_njalla_examples
######################################################################
sub nic_njalla_examples {
    return <<"EoEXAMPLE";

o 'njalla'

The 'njalla' protocol is used by DNS service offered by njal.la.

Configuration variables applicable to the 'njalla' protocol are:
  protocol=njalla              ##
  password=service-password    ## Generated password for your dynamic DNS record
  quietreply=no|yes            ## If yes return empty response on success with status 200 but print errors
  domain                       ## subdomain to update, use @ for base domain name, * for catch all

Example ${program}.conf file entries:
  ## single host update
  protocol=njalla                                             \\
  password=njal.la-key
  quietreply=no
  domain.com

EoEXAMPLE
}
######################################################################
## nic_njalla_update
##
## written by satrapes
##
## based on https://njal.la/docs/ddns/
## needs this url to update:
## https://njal.la/update?h=host_name&k=domain_password&a=your_ip
## response contains "code 200" on succesful completion
######################################################################
sub nic_njalla_update {
    debug("\nnic_njalla_update -------------------");

    foreach my $h (@_) {
        # Read input params
        my $ipv4 = delete $config{$h}{'wantipv4'};
        my $ipv6 = delete $config{$h}{'wantipv6'};
        my $quietreply = delete $config{$h}{'quietreply'};
        my $ip_output = '';

        # Build url
        my $url = "https://$config{$h}{'server'}/update/?h=$h&k=$config{$h}{'password'}";
        my $auto = 1;
        foreach my $ip ($ipv4, $ipv6) {
            next if (!$ip);
            $auto = 0;
            my $ipv  = ($ip eq ($ipv6 // '')) ? '6' : '4';
            my $type = ($ip eq ($ipv6 // '')) ? 'aaaa' : 'a';
            $ip_output .= " IP v$ipv: $ip,";
            $url .= "&$type=$ip";
        }
        $url .= (($auto eq 1)) ? '&auto' : '';
        $url .= (($quietreply eq 1)) ? '&quiet' : '';

        info("setting address to%s for %s", ($ip_output eq '') ? ' auto' : $ip_output, $h);
        verbose("UPDATE:", "updating %s", $h);
        debug("url: %s", $url);

        # Try to get URL
        my $reply = geturl(proxy => opt('proxy'), url => $url);
        my $response = '';
        if ($quietreply) {
            $reply =~ qr/invalid host or key/mp;
            $response = ${^MATCH};
            if (!$response) {
                success("updating %s: good: IP address set to %s", $h, $ip_output);
            }
            elsif ($response =~ /invalid host or key/) {
                failed("Invalid host or key");
            } else {
                failed("Unknown response");
            }
        } else {
            $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
            $response = eval {decode_json(${^MATCH})};
            # No response, declare as failed
            if (!defined($reply) || !$reply) {
                failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            } else {
                # Strip header
                if ($response->{status} == 401 && $response->{message} =~ /invalid host or key/) {
                    failed("Invalid host or key");
                } elsif ($response->{status} == 200 && $response->{message} =~ /record updated/) {
                    success("updating %s: good: IP address set to %s", $h, $response->{value}->{A});
                } else {
                    failed("Unknown response");
                }
            }
        }
    }
}

######################################################################
## nic_sitelutions_examples
######################################################################
sub nic_sitelutions_examples {
    return <<"EoEXAMPLE";

o 'sitelutions'

The 'sitelutions' protocol is used by DNS services offered by www.sitelutions.com.

Configuration variables applicable to the 'sitelutions' protocol are:
  protocol=sitelutions         ##
  server=fqdn.of.service       ## defaults to sitelutions.com
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  A_record_id                  ## Id of the A record for the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=sitelutions,                                         \\
  login=my-sitelutions.com-login,                               \\
  password=my-sitelutions.com-password                          \\
  my-sitelutions.com-id_of_A_record

EoEXAMPLE
}
######################################################################
## nic_sitelutions_update
##
## written by Mike W. Smith
##
## based on https://www.sitelutions.com/help/dynamic_dns_clients#updatespec
## needs this url to update:
## https://www.sitelutions.com/dnsup?id=990331&user=myemail@mydomain.com&pass=SecretPass&ip=192.168.10.4
## domain=domain.com&password=domain_password&ip=your_ip
##
######################################################################
sub nic_sitelutions_update {


    debug("\nnic_sitelutions_update -------------------");

    ## update each configured host
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        my $url;
        $url  = "https://$config{$h}{'server'}/dnsup";
        $url .= "?id=$h";
        $url .= "&user=$config{$h}{'login'}";
        $url .= "&pass=$config{$h}{'password'}";
        $url .= "&ip=";
        $url .= $ip if $ip;

        my $reply = geturl(proxy => opt('proxy'), url => $url);
        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        if (grep /success/i, @reply) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            warning("SENT:    %s", $url) unless opt('verbose');
            warning("REPLIED: %s", $reply);
            failed("updating %s: Invalid reply.", $h);
        }
    }
}

######################################################################

######################################################################
## nic_freedns_examples
######################################################################
sub nic_freedns_examples {
    return <<"EoEXAMPLE";

o 'freedns'

The 'freedns' protocol is used by DNS services offered by freedns.afraid.org.

Configuration variables applicable to the 'freedns' protocol are:
  protocol=freedns             ##
  server=fqdn.of.service       ## defaults to freedns.afraid.org
  login=service-login          ## login name and password registered with the service
  password=service-password    ##
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=freedns,                                             \\
  login=my-freedns.afraid.org-login,                            \\
  password=my-freedns.afraid.org-password                       \\
  myhost.afraid.com

EoEXAMPLE
}
######################################################################
## nic_freedns_update
##
## API v1 documented at https://freedns.afraid.org/api/
##
## An update requires two steps. The first is to get a list of records from:
##   https://freedns.afraid.org/api/?action=getdyndns&v=2&sha=<sha1sum of login|password>
## The returned list looks like:
##
##   hostname1.example.com|1.2.3.4|http://example/update/url1
##   hostname1.example.com|dead::beef|http://example/update/url2
##   hostname2.example.com|5.6.7.8|http://example/update/url3
##   hostname2.example.com|9.10.11.12|http://example/update/url4
##   hostname3.example.com|cafe::f00d|http://example/update/url5
##   hostname4.example.com|NULL|http://example/update/url6
##
## The record's columns are separated by '|'. The first is the hostname, the second is the current
## address, and the third is the record-specific update URL. There can be multiple records for the
## same host, and they can even have the same address type. To update an IP address the record
## must already exist of the type we want to update... We will not change a record type from
## an IPv4 to IPv6 or viz versa.  Records may exist with a NULL address which we will allow to be
## updated with an IPv4 address, not an IPv6.
##
## The second step is to visit the appropriate record's update URL with
## ?address=<ipv4-or-ipv6-address> appended. "Updated" in the result means success, "fail" means
## failure.
######################################################################
sub nic_freedns_update {
    debug("\nnic_freedns_update -------------------");
    # Separate the records that are currently holding IPv4 addresses from the records that are
    # currently holding IPv6 addresses so that we can avoid switching a record to a different
    # address type.
    my %recs_ipv4;
    my %recs_ipv6;
    my $url_tmpl = "https://$config{$_[0]}{'server'}/api/?action=getdyndns&v=2&sha=<credentials>";
    my $creds = sha1_hex("$config{$_[0]}{'login'}|$config{$_[0]}{'password'}");
    (my $url = $url_tmpl) =~ s/<credentials>/$creds/;

    my $reply = geturl(proxy => opt('proxy'),
                       url => $url
                      );
    my $record_list_error = '';
    if ($reply && header_ok($_[0], $reply)) {
        $reply =~ s/^.*?\n\n//s;  # Strip the headers.
        for (split("\n", $reply)) {
            my @rec = split(/\|/);
            next if ($#rec < 2);
            my $recs = is_ipv6($rec[1]) ? \%recs_ipv6 : \%recs_ipv4;
            $recs->{$rec[0]} = \@rec;
            # Update URL contains credentials that don't require login to use, so best to hide.
            debug("host: %s, current address: %s, update URL: <redacted>", $rec[0], $rec[1]);
        }
        if (keys(%recs_ipv4) + keys(%recs_ipv6) == 0) {
            chomp($reply);
            $record_list_error = "failed to get record list from $url_tmpl: $reply";
        }
    } else {
        $record_list_error = "failed to get record list from $url_tmpl";
    }

    foreach my $h (@_) {
        next if (!$h);
        my $ipv4 = delete $config{$h}{'wantipv4'};
        my $ipv6 = delete $config{$h}{'wantipv6'};

        if ($record_list_error ne '') {
            $config{$h}{'status-ipv4'} = 'failed' if ($ipv4);
            $config{$h}{'status-ipv6'} = 'failed' if ($ipv6);
            failed("updating %s: %s", $h, $record_list_error);
            next;
        }

        # IPv4 and IPv6 handling are similar enough to do in a loop...
        foreach my $ip ($ipv4, $ipv6) {
            next if (!$ip);
            my $ipv  = ($ip eq ($ipv6 // '')) ? '6' : '4';
            my $type = ($ip eq ($ipv6 // '')) ? 'AAAA' : 'A';
            my $rec  = ($ip eq ($ipv6 // '')) ? $recs_ipv6{$h}
                                              : $recs_ipv4{$h};
            if (!$rec) {
                failed("updating %s: Cannot set IPv$ipv to %s No '$type' record at FreeDNS", $h, $ip);
                next;
            }

            info("updating %s: setting IP address to %s", $h, $ip);
            $config{$h}{"status-ipv$ipv"} = 'failed';

            if ($ip eq $rec->[1]) {
                $config{$h}{"ipv$ipv"} = $ip;
                $config{$h}{'mtime'} = $now;
                $config{$h}{"status-ipv$ipv"} = 'good';
                success("updating %s: update not necessary, '$type' record already set to %s", $h, $ip)
                    if (!$daemon || opt('verbose'));
            } else {
                my $url = $rec->[2] . "&address=" . $ip;
                ($url_tmpl = $url) =~ s/\?.*\&/?<redacted>&/; # redact unique update token
                debug("updating: %s", $url_tmpl);

                my $reply = geturl(proxy => opt('proxy'),
                                   url => $url
                                  );
                if ($reply && header_ok($h, $reply)) {
                    $reply =~ s/^.*?\n\n//s;  # Strip the headers.
                    if ($reply =~ /Updated.*$h.*to.*$ip/) {
                        $config{$h}{"ipv$ipv"} = $ip;
                        $config{$h}{'mtime'} = $now;
                        $config{$h}{"status-ipv$ipv"} = 'good';
                        success("updating %s: good: IPv$ipv address set to %s", $h, $ip);
                    } else {
                        warning("SENT: %s", $url_tmpl) unless opt('verbose');
                        warning("REPLIED: %s", $reply);
                        failed("updating %s: Invalid reply.", $h);
                    }
                } else {
                    failed("updating %s: Could not connect to %s.", $h, $url_tmpl);
                }
            }
        }
    }
}

######################################################################
## nic_1984_examples
######################################################################
sub nic_1984_examples {
    return <<"EoEXAMPLE";

o '1984'

The '1984' protocol is used by DNS services offered by 1984.is.

Configuration variables applicable to the '1984' protocol are:
  protocol=1984                ##
  password=api-key             ## your API key
  fully.qualified.host         ## the domain to update

Example ${program}.conf file entries:
  ## single host update
  protocol=1984,                                                   \\
  password=my-1984-api-key,                                        \\
  myhost

EoEXAMPLE
}

######################################################################
## nic_1984_update
## https://api.1984.is/1.0/freedns/?apikey=xxx&domain=mydomain&ip=myip
## The response is a JSON document containing the following entries
## - ok: true or false depending on if the request was successful or not,
##       if the ip is the same as before this will be true,
## - msg: successes or why it is not working,
## - lookup: if domain or subdomain was not found lookup will contain a list of names tried
######################################################################
sub nic_1984_update {
    debug("\nnic_1984_update -------------------");
    foreach my $host (@_) {
        my $ip = delete $config{$host}{'wantip'};
        info("setting IP address to %s for %s", $ip, $host);
        verbose("UPDATE:", "updating %s", $host);

        my $url;
        $url  = "https://$config{$host}{'server'}/1.0/freedns/";
        $url .= "?apikey=$config{$host}{'password'}";
        $url .= "&domain=$host";
        $url .= "&ip=$ip";

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
        ) // '';
        if ($reply eq '') {
            failed("Updating %s: Could not connect to %s.", $host, $config{$host}{'server'});
            next;
        }
        next if !header_ok($host, $reply);

        # Strip header
        $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
        my $response = eval { decode_json(${^MATCH}) };
        if ($@) {
            failed("Updating %s: JSON decoding failure", $host);
            next;
        }
        unless ($response->{ok}) {
            failed("%s", $response->{msg});
        }

        if ($response->{msg} =~ /unaltered/) {
            success("Updating %s: skipped: IP was already set to %s", $host, $response->{ip});
        } else {
            success("%s -- Updated successfully to %s", $host, $response->{ip});
        }
    }
}

######################################################################
## nic_changeip_examples
######################################################################
sub nic_changeip_examples {
    return <<"EoEXAMPLE";

o 'changeip'

The 'changeip' protocol is used by DNS services offered by changeip.com.

Configuration variables applicable to the 'changeip' protocol are:
  protocol=changeip            ##
  server=fqdn.of.service       ## defaults to nic.changeip.com
  login=service-login          ## login name and password registered with the service
  password=service-password    ##
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=changeip,                                               \\
  login=my-my-changeip.com-login,                                  \\
  password=my-changeip.com-password                                \\
  myhost.changeip.org

EoEXAMPLE
}

######################################################################
## nic_changeip_update
##
## adapted by Michele Giorato
##
## https://nic.ChangeIP.com/nic/update?hostname=host.example.org&myip=66.185.162.19
##
######################################################################
sub nic_changeip_update {


    debug("\nnic_changeip_update -------------------");

    ## update each configured host
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        my $url;
        $url  = "https://$config{$h}{'server'}/nic/update";
        $url .= "?hostname=$h";
        $url .= "&ip=";
        $url .= $ip if $ip;

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        );
        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        if (grep /success/i, @reply) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            warning("SENT:    %s", $url) unless opt('verbose');
            warning("REPLIED: %s", $reply);
            failed("updating %s: Invalid reply.", $h);
        }
    }
}

######################################################################
## nic_godaddy_examples
##
## written by awalon
##
######################################################################
sub nic_godaddy_examples {
    return <<"EoEXAMPLE";

o 'godaddy'

The 'godaddy' protocol is used by DNS service offered by https://www.godaddy.com/domains.

Configuration variables applicable to the 'godaddy' protocol are:
  protocol=godaddy              ##
  login=my-generated-token      ## the token/key name provided by the API interface
  password=my-generated-secret  ## the secret provided by the API interface
  zone=domain.tld               ## the domain used for DNS update.
  ttl=600                       ## time to live of the record;
  hostname.domain.tld           ## hostname/subdomain

Example ${program}.conf file entries:
  ## single host update
  protocol=godaddy                                             \\
  login=my-generated-token                                     \\
  password=my-generated-secret                                 \\
  zone=example.com                                             \\
  hostname.example.com

  ## multiple host update to the DNS service
  protocol=godaddy                                             \\
  login=my-generated-token                                     \\
  password=my-generated-secret                                 \\
  zone=example.com                                             \\
  host1.example.com,host2.example.com
EoEXAMPLE
}
######################################################################
## nic_godaddy_update
######################################################################
sub nic_godaddy_update {
    debug("\nnic_godaddy_update --------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(server login password zone) ]);

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};

        # Update each set configured host.
        for my $host (@hosts) {
            my $ip = delete $config{$host}{'wantip'};
            my $zone = $config{$host}{'zone'};
            (my $hostname = $host) =~ s/\.\Q$zone\E$//;

            info("%s.%s -- Setting IP address to %s.", $hostname, $zone, $ip);
            verbose("UPDATE:", "updating %s.%s", $hostname, $zone);

            my $ipversion = is_ipv6($ip) ? "6" : "4";
            my $rrset_type = $ipversion == "6" ? "AAAA" : "A";
            my $data = encode_json([{
                data => $ip,
                defined($config{$host}{'ttl'}) ? (ttl => $config{$host}{'ttl'}) : (),
                name => $hostname,
                type => $rrset_type,
            }]);

            my $url = "https://$config{$host}{'server'}";
            $url .= "/${zone}/records/${rrset_type}/${hostname}";

            my $header = "Content-Type: application/json\n";
            $header .= "Accept: application/json\n";
            $header .= "Authorization: sso-key $config{$host}{'login'}:$config{$host}{'password'}\n";
            my $reply = geturl(
                proxy     => opt('proxy'),
                url       => $url,
                headers   => $header,
                method    => 'PUT',
                data      => $data,
            );
            unless ($reply) {
                failed("%s.%s -- Could not connect to %s.", $hostname, $zone, $config{$host}{'server'});
                next;
            }

            (my $status) = ($reply =~ m%^s*HTTP/.*\s+(\d+)%i);
            my $ok = header_ok($host, $reply);
            my $msg;
            $reply =~ s/^.*?\n\n//s; # extract payload
            my $response = eval { decode_json($reply) };
            if (!defined($response) && $status != "200") {
                $config{$host}{'status'} = "bad";

                failed("%s.%s -- Unexpected or empty service response, cannot parse data.", $hostname, $zone);
            } elsif (defined($response->{code})) {
                verbose("%s.%s -- %s - %s.", $hostname, $zone, $response->{code}, $response->{message});
            }
            if ($ok) {
                # read data
                $config{$host}{'ip'}     = $ip;
                $config{$host}{'mtime'}  = $now;
                $config{$host}{'status'} = "good";

                success("%s.%s -- Updated successfully to %s (status: %s).", $hostname, $zone, $ip, $status);
                next;
            } elsif ($status == "400") {
                $msg = 'GoDaddy API URL ($url) was malformed.';
            } elsif ($status == "401") { # authentication error
                if ($config{$host}{'login'} && $config{$host}{'login'}) {
                    $msg  = 'login or password option incorrect.';
                } else {
                    $msg  = 'login or password option missing.';
                }
                $msg .= ' Correct values can be obtained from from https://developer.godaddy.com/keys/.';
            } elsif ($status == "403") {
                $msg = 'Customer identified by login and password options denied permission.';
            } elsif ($status == "404") {
                $msg = "\"${hostname}.${zone}\" not found at GoDaddy, please check zone option and login/password.";
            } elsif ($status == "422") {
                $msg = "\"${hostname}.${zone}\" has invalid domain or lacks A/AAAA record.";
            } elsif ($status == "429") {
                $msg = 'Too many requests to GoDaddy within brief period.';
            } elsif ($status == "503") {
                $msg = "\"${hostname}.${zone}\" is unavailable.";
            } else {
                $msg = 'Unexpected service response.';
            }

            $config{$host}{'status'} = "bad";
            failed("%s.%s -- %s", $hostname, $zone, $msg);
        }
    }
}

######################################################################
## nic_googledomains_examples
##
## written by Nelson Araujo
##
######################################################################
sub nic_googledomains_examples {
    return <<"EoEXAMPLE";
o 'googledomains'

The 'googledomains' protocol is used by DNS service offered by www.google.com/domains.

Configuration variables applicable to the 'googledomains' protocol are:
  protocol=googledomains       ##
  login=service-login          ## the user name provided by the admin interface
  password=service-password    ## the password provided by the admin interface
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=googledomains,                                      \\
  login=my-generated-user-name,                                \\
  password=my-genereated-password                              \\
  myhost.com

  ## multiple host update to the custom DNS service
  protocol=googledomains,                                      \\
  login=my-generated-user-name,                                \\
  password=my-genereated-password                              \\
  my-toplevel-domain.com,my-other-domain.com
EoEXAMPLE
}
######################################################################
## nic_googledomains_update
######################################################################
sub nic_googledomains_update {
    debug("\nnic_googledomains_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(server login password) ]);

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};
        my $key   = $hosts[0];
        my $ip    = $config{$key}{'wantip'};

        # FQDNs
        for my $host (@hosts) {
            delete $config{$host}{'wantip'};

            info("setting IP address to %s for %s", $ip, $host);
            verbose("UPDATE:", "updating %s", $host);

            # Update the DNS record
            my $url = "https://$config{$host}{'server'}/nic/update";
            $url .= "?hostname=$host";
            $url .= "&myip=";
            $url .= $ip if $ip;

            my $reply = geturl(
                proxy => opt('proxy'),
                url => $url,
                login => $config{$host}{'login'},
                password => $config{$host}{'password'},
            );
            unless ($reply) {
                failed("updating %s: Could not connect to %s.", $host, $config{$host}{'server'});
                next;
            }
            next if !header_ok($host, $reply);

            # Cache
            $config{$host}{'ip'}     = $ip;
            $config{$host}{'mtime'}  = $now;
            $config{$host}{'status'} = 'good';
        }
    }
}

######################################################################
## nic_mythicdyn_examples
##
## written by Reuben Thomas
##
######################################################################
sub nic_mythicdyn_examples {
    return <<"EoEXAMPLE";
o 'mythicdyn'

The 'mythicdyn' protocol is used by the Dynamic DNS service offered by
www.mythic-beasts.com.

Configuration variables applicable to the 'mythicdyn' protocol are:
  protocol=mythicdyn           ##
  ipv6=no|yes                  ## whether to set an A record (default, ipv6=no)
                               ## or AAAA record (ipv6=yes).
  login=service-login          ## the user name provided by the admin interface
  password=service-password    ## the password provided by the admin interface
  fully.qualified.host         ## the host registered with the service

Note: this service automatically sets the IP address to that from which the
request comes, so the IP address detected by ddclient is only used to keep
track of when it needs updating.

Example ${program}.conf file entries:
  ## Single host update.
  protocol=mythicdyn,                       \\
  login=service-login                       \\
  password=service-password,                \\
  host.example.com

  ## Multiple host update.
  protocol=mythicdyn,                       \\
  login=service-login                       \\
  password=service-password,                \\
  hosta.example.com,hostb.sub.example.com
EoEXAMPLE
}
######################################################################
## nic_mythicdyn_update
######################################################################
sub nic_mythicdyn_update {
    debug("\nnic_mythicdyn_update --------------------");

    # Update each set configured host.
    foreach my $h (@_) {
        info("%s -- Setting IP address.", $h);

        my $ipversion = $config{$h}{'ipv6'} ? '6' : '4';

        my $reply = geturl(
            proxy     => opt('proxy'),
            url       => "https://ipv$ipversion.$config{$h}{'server'}/dns/v2/dynamic/$h",
            method    => 'POST',
            login     => $config{$h}{'login'},
            password  => $config{$h}{'password'},
            ipversion => $ipversion,
        );
        unless ($reply) {
            failed("Updating service %s failed: %s", $h, $config{$h}{'server'});
            next;
        }

        my $ok = header_ok($h, $reply);
        if ($ok) {
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = "good";

            success("%s -- Updated successfully.", $h);
        } else {
            failed("%s -- Failed to update.", $h);
        }
    }
}

######################################################################
## nic_nsupdate_examples
######################################################################
sub nic_nsupdate_examples {
    return <<"EoEXAMPLE";
o 'nsupdate'

The 'nsupdate' protocol is used to submit Dynamic DNS Update requests as
defined in RFC2136 to a name server using the 'nsupdate' command line
utility part of ISC BIND.  Dynamic DNS updates allow resource records to
be added or removed from a zone configured for dynamic updates through
DNS requests protected using TSIG.  BIND ships with 'ddns-confgen', a
utility to generate sample configurations and instructions for both the
server and the client.  See nsupdate(1) and ddns-confgen(8) for details.

Configuration variables applicable to the 'nsupdate' protocol are:
  protocol=nsupdate
  server=ns1.example.com       ## name or IP address of the DNS server to send
                               ## the update requests to; usually master for
                               ## zone, but slaves should forward the request
  password=tsig.key            ## path and name of the symmetric HMAC key file
                               ## to use for TSIG signing of the request
                               ## (as generated by 'ddns-confgen -q' and
                               ## configured on server in 'grant' statement)
  zone=dyn.example.com         ## forward zone that is to be updated
  ttl=600                      ## time to live of the record;
                               ## defaults to 600 seconds
  tcp=off|on                   ## nsupdate uses UDP by default, and switches to
                               ## TCP if the update is too large to fit in a
                               ## UDP datagram; this setting forces TCP;
                               ## defaults to off
  login=/usr/bin/nsupdate      ## path and name of nsupdate binary;
                               ## defaults to '/usr/bin/nsupdate'
  <hostname>                   ## fully qualified hostname to update

Example ${program}.conf file entries:
  ## single host update
  protocol=nsupdate \\
  server=ns1.example.com \\
  password=/etc/${program}/dyn.example.com.key \\
  zone=dyn.example.com \\
  ttl=3600 \\
  myhost.dyn.example.com

EoEXAMPLE
}

######################################################################
## nic_nsupdate_update
## by Daniel Roethlisberger <daniel@roe.ch>
######################################################################
sub nic_nsupdate_update {
    debug("\nnic_nsupdate_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(login password server zone) ]);

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts   = @{$groups{$sig}};
        my $hosts   = join(',', @hosts);
        my $h       = $hosts[0];
        my $binary  = $config{$h}{'login'};
        my $keyfile = $config{$h}{'password'};
        my $server  = $config{$h}{'server'};
        ## nsupdate requires a port number to be separated by whitepace, not colon
        $server =~ s/:/ /;
        my $zone       = $config{$h}{'zone'};
        my $ip         = $config{$h}{'wantip'};
        my $recordtype = '';
        if (is_ipv6($ip)) {
            $recordtype = 'AAAA';
        } else {
            $recordtype = 'A';
        }
        delete $config{$_}{'wantip'} foreach @hosts;

        info("setting IP address to %s for %s", $ip, $hosts);
        verbose("UPDATE:", "updating %s", $hosts);

        ## send separate requests for each zone with all hosts in that zone
        my $instructions = <<"EoINSTR1";
server $server
zone $zone.
EoINSTR1
        foreach (@hosts) {
            $instructions .= <<"EoINSTR2";
update delete $_. $recordtype
update add $_. $config{$_}{'ttl'} $recordtype $ip
EoINSTR2
        }
        $instructions .= <<"EoINSTR3";
send
EoINSTR3
        my $command = "$binary -k $keyfile";
        $command .= " -v" if ynu($config{$h}{'tcp'}, 1, 0, 0);
        $command .= " -d" if (opt('debug'));
        verbose("UPDATE:", "nsupdate command is: %s", $command);
        verbose("UPDATE:", "nsupdate instructions are:\n%s", $instructions);

        my $status = pipecmd($command, $instructions);
        if ($status eq 1) {
            foreach (@hosts) {
                $config{$_}{'ip'}    = $ip;
                $config{$_}{'mtime'} = $now;
                success("updating %s: %s: IP address set to %s", $_, $status, $ip);
            }
        } else {
            foreach (@hosts) {
                failed("updating %s", $_);
            }
        }
    }
}

######################################################################

######################################################################
## nic_cloudflare_examples
##
## written by Ian Pye
##
######################################################################
sub nic_cloudflare_examples {
    return <<"EoEXAMPLE";
o 'cloudflare'

The 'cloudflare' protocol is used by DNS service offered by www.cloudflare.com.

Configuration variables applicable to the 'cloudflare' protocol are:
  protocol=cloudflare          ##
  server=fqdn.of.service       ## defaults to api.cloudflare.com/client/v4
  login=service-login          ## login email when using a global API key
  password=service-password    ## Global API key, or an API token. If using an API token, it must have the permissions "Zone - DNS - Edit" and "Zone - Zone - Read". The Zone resources must be "Include - All zones".
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update using a global API key
  protocol=cloudflare,                                         \\
  zone=dns.zone,                                               \\
  login=my-cloudflare.com-login,                               \\
  password=my-cloudflare-global-key                            \\
  myhost.com

  ## single host update using an API token
  protocol=cloudflare,                                         \\
  zone=dns.zone,                                               \\
  login=token,                                                 \\
  password=cloudflare-api-token                                \\
  myhost.com

  ## multiple host update to the custom DNS service
  protocol=cloudflare,                                         \\
  zone=dns.zone,                                               \\
  login=my-cloudflare.com-login,                               \\
  password=my-cloudflare-global-api-key                        \\
  my-toplevel-domain.com,my-other-domain.com
EoEXAMPLE
}
######################################################################
## nic_cloudflare_update
######################################################################
sub nic_cloudflare_update {
    debug("\nnic_cloudflare_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(ssh login password server wildcard mx backupmx zone) ]);

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};
        my $hosts = join(',', @hosts);
        my $key   = $hosts[0];

        my $headers = "Content-Type: application/json\n";
        if ($config{$key}{'login'} eq 'token') {
            $headers .= "Authorization: Bearer $config{$key}{'password'}\n";
        } else {
            $headers .= "X-Auth-Email: $config{$key}{'login'}\n";
            $headers .= "X-Auth-Key: $config{$key}{'password'}\n";
        }

        # FQDNs
        for my $domain (@hosts) {
            my $ipv4  = delete $config{$domain}{'wantipv4'};
            my $ipv6  = delete $config{$domain}{'wantipv6'};

            info("getting Cloudflare Zone ID for %s", $domain);

            # Get zone ID
            my $url = "https://$config{$key}{'server'}/zones/?";
            $url .= "name=" . $config{$key}{'zone'};

            my $reply = geturl(proxy => opt('proxy'),
                               url => $url,
                               headers => $headers
                              );
            unless ($reply && header_ok($domain, $reply)) {
                failed("updating %s: Could not connect to %s.", $domain, $config{$key}{'server'});
                next;
            }

            # Strip header
            $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
            my $response = eval {decode_json(${^MATCH})};
            unless ($response && $response->{result}) {
                failed("updating %s: invalid json or result.", $domain);
                next;
            }

            # Pull the ID out of the json, messy
            my ($zone_id) = map {$_->{name} eq $config{$key}{'zone'} ? $_->{id} : ()} @{$response->{result}};
            unless ($zone_id) {
                failed("updating %s: No zone ID found.", $config{$key}{'zone'});
                next;
            }
            info("Zone ID is %s", $zone_id);


            # IPv4 and IPv6 handling are similar enough to do in a loop...
            foreach my $ip ($ipv4, $ipv6) {
                next if (!$ip);
                my $ipv  = ($ip eq ($ipv6 // '')) ? '6' : '4';
                my $type = ($ip eq ($ipv6 // '')) ? 'AAAA' : 'A';

                info("updating %s: setting IPv$ipv address to %s", $domain, $ip);
                $config{$domain}{"status-ipv$ipv"} = 'failed';

                # Get DNS 'A' or 'AAAA' record ID
                $url = "https://$config{$key}{'server'}/zones/$zone_id/dns_records?";
                $url .= "type=$type&name=$domain";
                $reply = geturl(proxy => opt('proxy'),
                                url => $url,
                                headers => $headers
                               );
                unless ($reply && header_ok($domain, $reply)) {
                    failed("updating %s: Could not connect to %s.", $domain, $config{$key}{'server'});
                    next;
                }
                # Strip header
                $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
                $response = eval {decode_json(${^MATCH})};
                unless ($response && $response->{result}) {
                    failed("updating %s: invalid json or result.", $domain);
                    next;
                }
                # Pull the ID out of the json, messy
                my ($dns_rec_id) = map {$_->{name} eq $domain ? $_->{id} : ()} @{$response->{result}};
                unless($dns_rec_id) {
                    failed("updating %s: Cannot set IPv$ipv to %s No '$type' record at Cloudflare", $domain, $ip);
                    next;
                }
                debug("updating %s: DNS '$type' record ID: $dns_rec_id", $domain);
                # Set domain
                $url = "https://$config{$key}{'server'}/zones/$zone_id/dns_records/$dns_rec_id";
                my $data = "{\"content\":\"$ip\"}";
                $reply = geturl(proxy => opt('proxy'),
                                url => $url,
                                headers => $headers,
                                method => "PATCH",
                                data => $data
                               );
                unless ($reply && header_ok($domain, $reply)) {
                    failed("updating %s: Could not connect to %s.", $domain, $config{$domain}{'server'});
                    next;
                }
                # Strip header
                $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
                $response = eval {decode_json(${^MATCH})};
                if ($response && $response->{result}) {
                    success("updating %s: IPv$ipv address set to %s", $domain, $ip);
                    $config{$domain}{"ipv$ipv"} = $ip;
                    $config{$domain}{'mtime'} = $now;
                    $config{$domain}{"status-ipv$ipv"} = 'good';
                } else {
                    failed("updating %s: invalid json or result.", $domain);
                }
            }
        }
    }
}

######################################################################
## nic_hetzner_examples
##
## written by Joerg Werner
##
######################################################################
sub nic_hetzner_examples {
    return <<"EoEXAMPLE";
o 'hetzner'

The 'hetzner' protocol is used by DNS service offered by www.hetzner.com.

Configuration variables applicable to the 'hetzner' protocol are:
  protocol=hetzner             ##
  server=fqdn.of.service       ## can be omitted, defaults to dns.hetzner.com/api/v1
  password=service-password    ## API token
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  protocol=hetzner,                                            \\
  zone=dns.zone,                                               \\
  password=my-hetzner-api-token                                \\
  my-toplevel-domain.com,my-other-domain.com
EoEXAMPLE
}
######################################################################
## nic_hetzner_update
######################################################################
sub nic_hetzner_update {
    debug("\nnic_hetzner_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(ssh login password server wildcard mx backupmx zone) ]);

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts = @{$groups{$sig}};
        my $hosts = join(',', @hosts);
        my $key   = $hosts[0];

        my $headers = "Auth-API-Token: $config{$key}{'password'}\n";
        $headers .= "Content-Type: application/json";

        # FQDNs
        for my $domain (@hosts) {
            (my $hostname = $domain) =~ s/\.$config{$key}{zone}$//;
            my $ipv4  = delete $config{$domain}{'wantipv4'};
            my $ipv6  = delete $config{$domain}{'wantipv6'};

            info("getting Hetzner Zone ID for %s", $domain);

            # Get zone ID
            my $url = "https://$config{$key}{'server'}/zones?name=" . $config{$key}{'zone'};

            my $reply = geturl(proxy => opt('proxy'),
                               url => $url,
                               headers => $headers
                              );
            unless ($reply && header_ok($domain, $reply)) {
                failed("updating %s: Could not connect to %s.", $domain, $config{$key}{'server'});
                next;
            }

            # Strip header
            $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
            my $response = eval {decode_json(${^MATCH})};
            unless ($response && $response->{zones}) {
                failed("updating %s: invalid json or result.", $domain);
                next;
            }

            # Pull the ID out of the json, messy
            my ($zone_id) = map {$_->{name} eq $config{$key}{'zone'} ? $_->{id} : ()} @{$response->{zones}};
            unless ($zone_id) {
                failed("updating %s: No zone ID found.", $config{$key}{'zone'});
                next;
            }
            info("Zone ID is %s", $zone_id);


            # IPv4 and IPv6 handling are similar enough to do in a loop...
            foreach my $ip ($ipv4, $ipv6) {
                next if (!$ip);
                my $ipv  = ($ip eq ($ipv6 // '')) ? '6' : '4';
                my $type = ($ip eq ($ipv6 // '')) ? 'AAAA' : 'A';

                info("updating %s: setting IPv$ipv address to %s", $domain, $ip);
                $config{$domain}{"status-ipv$ipv"} = 'failed';

                # Get DNS 'A' or 'AAAA' record ID
                $url = "https://$config{$key}{'server'}/records?zone_id=$zone_id";
                $reply = geturl(proxy => opt('proxy'),
                                url => $url,
                                headers => $headers
                               );
                unless ($reply && header_ok($domain, $reply)) {
                    failed("updating %s: Could not connect to %s.", $domain, $config{$key}{'server'});
                    next;
                }
                # Strip header
                $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
                $response = eval {decode_json(${^MATCH})};
                unless ($response && $response->{records}) {
                    failed("updating %s: invalid json or result.", $domain);
                    next;
                }
                # Pull the ID out of the json, messy
                my ($dns_rec_id) = map { ($_->{name} eq $hostname && $_->{type} eq $type) ? $_->{id} : ()} @{$response->{records}};

                # Set domain
                my $http_method="";
                if ($dns_rec_id)
                {
                    debug("updating %s: DNS '$type' record ID: $dns_rec_id", $domain);
                    $url   = "https://$config{$key}{'server'}/records/$dns_rec_id";
                    $http_method = "PUT";
                } else {
                    debug("creating %s: DNS '$type'", $domain);
                    $url   = "https://$config{$key}{'server'}/records";
                    $http_method = "POST";
                }
                my $data = "{\"zone_id\":\"$zone_id\", \"name\": \"$hostname\", \"value\": \"$ip\", \"type\": \"$type\", \"ttl\": $config{$domain}{'ttl'}}";

                $reply = geturl(proxy => opt('proxy'),
                                url => $url,
                                headers => $headers,
                                method => $http_method,
                                data => $data
                               );
                unless ($reply && header_ok($domain, $reply)) {
                    failed("updating %s: Could not connect to %s.", $domain, $config{$domain}{'server'});
                    next;
                }
                # Strip header
                $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
                $response = eval {decode_json(${^MATCH})};
                if ($response && $response->{record}) {
                    success("updating %s: IPv$ipv address set to %s", $domain, $ip);
                    $config{$domain}{"ipv$ipv"} = $ip;
                    $config{$domain}{'mtime'} = $now;
                    $config{$domain}{"status-ipv$ipv"} = 'good';
                } else {
                    failed("updating %s: invalid json or result.", $domain);
                }
            }
        }
    }
}

######################################################################
## nic_yandex_examples
######################################################################
sub nic_yandex_examples {
    return <<"EoEXAMPLE";
o Yandex

The 'yandex' protocol is used to by DNS service offered by Yandex.

Configuration variables applicable to the 'yandex' protocol are:
  protocol=yandex             ##
  server=fqdn.of.service       ## defaults to pddimp.yandex.ru
  login=dns.zone               ## Your zone name
  password=pdd-token           ## PDD token for authentication
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=yandex,                                              \\
  login=myhost.com,                                             \\
  password=123456789ABCDEF0000000000000000000000000000000000000 \\
  record.myhost.com

  ## multiple host update
  protocol=yandex,                                              \\
  login=myhost.com,                                             \\
  password=123456789ABCDEF0000000000000000000000000000000000000 \\
  record.myhost.com,other.myhost.com
EoEXAMPLE
}
######################################################################
## nic_yandex_update
##
## written by Denis Akimkin
##
######################################################################
sub nic_yandex_update {
    debug("\nnic_yandex_update -------------------");

    ## group hosts with identical attributes together
    my %groups = group_hosts_by([ @_ ], [ qw(server login pasword) ]);

    ## update each set of hosts that had similar configurations
    foreach my $sig (keys %groups) {
        my @hosts   = @{$groups{$sig}};
        my $key     = $hosts[0];
        my $ip      = $config{$key}{'wantip'};
        my $headers = "PddToken: $config{$key}{'password'}\n";

        # FQDNs
        for my $host (@hosts) {
            delete $config{$host}{'wantip'};

            info("setting IP address to %s for %s", $ip, $host);
            verbose("UPDATE:", "updating %s", $host);

            # Get record ID for host
            my $url = "https://$config{$host}{'server'}/api2/admin/dns/list?";
            $url .= "domain=";
            $url .= $config{$key}{'login'};
            my $reply = geturl(proxy => opt('proxy'), url => $url, headers => $headers);
            unless ($reply) {
                failed("updating %s: Could not connect to %s.", $host, $config{$key}{'server'});
                next;
            }
            next if !header_ok($host, $reply);

            # Strip header
            $reply =~ s/^.*?\n\n//s;
            my $response = eval { decode_json($reply) };
            if ($response->{success} eq 'error') {
                failed("%s", $response->{error});
                next;
            }

            # Pull the ID out of the json
            my ($id) = map { $_->{fqdn} eq $host ? $_->{record_id} : () } @{$response->{records}};
            unless ($id) {
                failed("updating %s: DNS record ID not found.", $host);
                next;
            }

            # Update the DNS record
            $url = "https://$config{$host}{'server'}/api2/admin/dns/edit";
            my $data = "domain=";
            $data .= $config{$key}{'login'};
            $data .= "&record_id=";
            $data .= $id;
            $data .= "&content=";
            $data .= $ip if $ip;

            $reply = geturl(
                proxy => opt('proxy'),
                url => $url,
                headers => $headers,
                method => 'POST',
                data => $data,
            );
            unless ($reply) {
                failed("updating %s: Could not connect to %s.", $host, $config{$host}{'server'});
                next;
            }
            next if !header_ok($host, $reply);

            # Strip header
            $reply =~ s/^.*?\n\n//s;
            $response = eval { decode_json($reply) };
            if ($response->{success} eq 'error') {
                failed("%s", $response->{error});
            } else {
                success("%s -- Updated Successfully to %s", $host, $ip);
            }

            # Cache
            $config{$host}{'ip'}     = $ip;
            $config{$host}{'mtime'}  = $now;
            $config{$host}{'status'} = 'good';
        }
    }
}

######################################################################
## nic_duckdns_examples
######################################################################
sub nic_duckdns_examples {
    return <<"EoEXAMPLE";
o 'duckdns'

The 'duckdns' protocol is used by the free
dynamic DNS service offered by www.duckdns.org.
Check https://www.duckdns.org/install.jsp?tab=linux-cron for API

Configuration variables applicable to the 'duckdns' protocol are:
  protocol=duckdns               ##
  server=www.fqdn.of.service   ## defaults to www.duckdns.org
  password=service-password    ## password (token) registered with the service
  non-fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=duckdns,        \\
  password=your_password,  \\
  myhost

EoEXAMPLE
}

######################################################################
## nic_duckdns_update
## by George Kranis (copypasta from nic_dtdns_update)
## https://www.duckdns.org/update?domains=mydomain1,mydomain2&token=xxxx-xxx-xx-x&ip=x.x.x.x
## response contains OK or KO
######################################################################
sub nic_duckdns_update {
    debug("\nnic_duckdns_update -------------------");

    ## update each configured host
    ## should improve to update in one pass
    foreach my $h (@_) {
        my $ipv4 = delete $config{$h}{'wantipv4'};
        my $ipv6 = delete $config{$h}{'wantipv6'};
        info("setting IPv4 address to %s for %s", $ipv4, $h) if $ipv4;
        info("setting IPv6 address to %s for %s", $ipv6, $h) if $ipv6;
        verbose("UPDATE:", "updating %s", $h);

        # Set the URL that we're going to to update
        my $url;
        $url  = "https://$config{$h}{'server'}/update";
        $url .= "?domains=";
        $url .= $h;
        $url .= "&token=";
        $url .= $config{$h}{'password'};
        $url .= "&ip=$ipv4" if $ipv4;
        $url .= "&ipv6=$ipv6" if $ipv6;

        # Try to get URL
        my $reply = geturl(proxy => opt('proxy'), url => $url);

        # No response, declare as failed
        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        my $state = 'noresult';
        my $line = '';

        foreach $line (@reply) {
            if ($line eq 'OK') {
                $config{$h}{'ipv4'}   = $ipv4 if $ipv4;
                $config{$h}{'ipv6'}   = $ipv6 if $ipv6;
                $config{$h}{'mtime'}  = $now;
                $config{$h}{'status'} = 'good';
                $config{$h}{'status-ipv4'} = 'good' if $ipv4;
                $config{$h}{'status-ipv6'} = 'good' if $ipv6;
                $state = 'result';
                success("updating %s: good: IPv4 address set to %s", $h, $ipv4) if $ipv4;
                success("updating %s: good: IPv6 address set to %s", $h, $ipv6) if $ipv6;

            } elsif ($line eq 'KO') {
                $config{$h}{'status'} = 'failed';
                $config{$h}{'status-ipv4'} = 'failed' if $ipv4;
                $config{$h}{'status-ipv6'} = 'failed' if $ipv6;
                $state = 'result';
                failed("updating %s: Server said: '%s'", $h, $line);
            }
        }

        if ($state eq 'noresult') {
            failed("updating %s: Server said: '%s'", $h, $line);
        }
    }
}

######################################################################
## nic_freemyip_examples
######################################################################
sub nic_freemyip_examples {
    return <<"EoEXAMPLE";
o 'freemyip'

The 'freemyip' protocol is used by the free
dynamic DNS service available at freemyip.com.
API is documented here: https://freemyip.com/help.py

Configuration variables applicable to the 'freemyip' protocol are:
  protocol=freemyip               ##
  password=service-token             ## token for your domain
  non-fully.qualified.host        ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=freemyip,                                     \\
  password=35a6b8d65c6e67c7f78cca65cd                    \\
  myhost

EoEXAMPLE
}

######################################################################
## nic_freemyip_update
## by Cadence (reused code from nic_duckdns)
## https://freemyip.com/update?token=ec54b4b64db27fe8873c7f7&domain=myhost
## response contains OK or ERROR
######################################################################
sub nic_freemyip_update {
    debug("\nnic_freemyip_update -------------------");

    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        # Set the URL that we're going to to update
        my $url;
        $url  = "https://$config{$h}{'server'}/update";
        $url .= "?token=";
        $url .= $config{$h}{'password'};
        $url .= "&domain=";
        $url .= $h;

        # Try to get URL
        my $reply = geturl(proxy => opt('proxy'), url => $url);

        # No response, declare as failed
        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        my $returned = pop(@reply);
        if ($returned =~ /OK/) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            failed("updating %s: Server said: '%s'", $h, $returned);
        }
    }
}

######################################################################
## nic_woima_examples
######################################################################
sub nic_woima_examples {
    return <<"EoEXAMPLE";
o 'woima'

The 'woima' protocol is used by the free
dynamic DNS service offered by woima.fi.
It offers also nameservers for own domains for free.
Dynamic DNS service for own domains is not free.

Configuration variables applicable to the 'woima' protocol are:
  protocol=woima               ##
  server=fqdn.of.service       ## defaults to dyn.woima.fi
  script=/path/to/script       ## defaults to /nic/update
  backupmx=no|yes              ## indicates that this host is the primary MX for the domain.
  static=no|yes                ## indicates that this host has a static IP address.
  custom=no|yes                ## indicates that this host is a 'custom' top-level domain name.
  mx=any.host.domain           ## a host MX'ing for this host definition.
  wildcard=no|yes              ## add a DNS wildcard CNAME record that points to {host}
  login=service-login          ## login name and password  registered with the service
  password=service-password    ##
  fully.qualified.host         ## the host registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=woima,                                           \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password                           \\
  myhost.dyndns.org

  ## multiple host update with wildcard'ing mx, and backupmx
  protocol=woima,                                           \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password,                          \\
  mx=a.host.willing.to.mx.for.me,backupmx=yes,wildcard=yes  \\
  myhost.dyndns.org,my2ndhost.dyndns.org

  ## multiple host update to the custom DNS service
  protocol=woima,                                           \\
  login=my-dyndns.org-login,                                \\
  password=my-dyndns.org-password                           \\
  my-toplevel-domain.com,my-other-domain.com
EoEXAMPLE
}
######################################################################
## nic_woima_update
######################################################################
sub nic_woima_update {
    debug("\nnic_woima_update -------------------");

    my %errors = (
        'badauth'  => 'Bad authorization (username or password)',
        'badsys'   => 'The system parameter given was not valid',

        'notfqdn'  => 'A Fully-Qualified Domain Name was not provided',
        'nohost'   => 'The hostname specified does not exist in the database',
        '!yours'   => 'The hostname specified exists, but not under the username currently being used',
        '!donator' => 'The offline setting was set, when the user is not a donator',
        '!active'  => 'The hostname specified is in a Custom DNS domain which has not yet been activated.',
        'abuse',   => 'The hostname specified is blocked for abuse; you should receive an email notification ' .
                      'which provides an unblock request link.  More info can be found on ' .
                      'https://www.dyndns.com/support/abuse.html',

        'numhost'  => 'System error: Too many or too few hosts found. Contact support@dyndns.org',
        'dnserr'   => 'System error: DNS error encountered. Contact support@dyndns.org',

        'nochg'    => 'No update required; unnecessary attempts to change to the current address are considered abusive',
    );

    for my $h (@_) {
        my $ip = $config{$h}{'wantip'};
        delete $config{$h}{'wantip'};

        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        ## Select the DynDNS system to update
        ## TODO: endpoint does not support https with functioning certificate. Remove?
        my $url = "http://$config{$h}{'server'}$config{$h}{'script'}?system=";
        if ($config{$h}{'custom'}) {
            warning("updating %s: 'custom' and 'static' may not be used together. ('static' ignored)", $h)
                if $config{$h}{'static'};
            $url .= 'custom';

        } elsif ($config{$h}{'static'}) {
            $url .= 'statdns';

        } else {
            $url .= 'dyndns';
        }

        $url .= "&hostname=$h";
        $url .= "&myip=";
        $url .= $ip            if $ip;

        ## some args are not valid for a custom domain.
        $url .= "&wildcard=ON" if ynu($config{$h}{'wildcard'}, 1, 0, 0);
        if ($config{$h}{'mx'}) {
            $url .= "&mx=$config{$h}{'mx'}";
            $url .= "&backmx=" . ynu($config{$h}{'backupmx'}, 'YES', 'NO');
        }

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        );
        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply      = split /\n/, $reply;
        my $state      = 'header';
        my $returnedip = $ip;

        foreach my $line (@reply) {
            if ($state eq 'header') {
                $state = 'body';

            } elsif ($state eq 'body') {
                $state = 'results' if $line eq '';

            } elsif ($state =~ /^results/) {
                $state = 'results2';

                # bug #10: some dyndns providers does not return the IP so
                # we can't use the returned IP
                my ($status, $returnedip) = split / /, lc $line;
                $ip = $returnedip if (not $ip);

                $config{$h}{'status'} = $status;
                if ($status eq 'good') {
                    $config{$h}{'ip'}    = $ip;
                    $config{$h}{'mtime'} = $now;
                    success("updating %s: %s: IP address set to %s", $h, $status, $ip);

                } elsif (exists $errors{$status}) {
                    if ($status eq 'nochg') {
                        warning("updating %s: %s: %s", $h, $status, $errors{$status});
                        $config{$h}{'ip'}     = $ip;
                        $config{$h}{'mtime'}  = $now;
                        $config{$h}{'status'} = 'good';

                    } else {
                        failed("updating %s: %s: %s", $h, $status, $errors{$status});
                    }

                } elsif ($status =~ /w(\d+)(.)/) {
                    my ($wait, $units) = ($1, lc $2);
                    my ($sec,  $scale) = ($wait, 1);

                    ($scale, $units) = (1, 'seconds')   if $units eq 's';
                    ($scale, $units) = (60, 'minutes')  if $units eq 'm';
                    ($scale, $units) = (60*60, 'hours') if $units eq 'h';

                    $sec = $wait * $scale;
                    $config{$h}{'wtime'} = $now + $sec;
                    warning("updating %s: %s: wait %s %s before further updates", $h, $status, $wait, $units);

                } else {
                    failed("updating %s: unexpected status (%s)", $h, $line);
                }
            }
        }
        failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'})
            if $state ne 'results2';
    }
}

######################################################################
## nic_dondominio_examples
######################################################################
sub nic_dondominio_examples {
    return <<"EoEXAMPLE";
o 'dondominio'
The 'dondominio' protocol is used by DNS service offered by www.dondominio.com/ .
API information and user instructions available at: https://dev.dondominio.com/dondns/docs/api/
Configuration variables applicable to the 'dondominio' protocol are:
  protocol=dondominio          ##
  login=service-login          ## the username registered with the service
  password=dondominio-apikey   ## API key provided by dondominio -see link above-
  fully.qualified.host         ## the host registered with the service.
Example ${program}.conf file entries:
  ## single host update
  protocol=dondominio,                                   \\
  login=my-generated-user-name,                          \\
  password=dondominio-apikey                             \\
  myhost.tld

EoEXAMPLE
}

######################################################################
## nic_dondominio_examples
######################################################################

sub nic_dondominio_update {
    debug("\nnic_dondominio_update -------------------");

    ## update each configured host
    ## should improve to update in one pass
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);

        # Set the URL that we're going to update
        my $url;
        $url  = "https://$config{$h}{'server'}/plain/";
        $url .= "?user=";
        $url .= $config{$h}{'login'};
        $url .= "&password=";
        $url .= $config{$h}{'password'};
        $url .= "&host=";
        $url .= $h;
        $url .= "&ip=";
        $url .= $ip if $ip;


        # Try to get URL
        my $reply = geturl(proxy => opt('proxy'), url => $url);

        # No response, declare as failed
        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        my $returned = pop(@reply);
        if ($returned =~ /OK/) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            failed("updating %s: Server said: '%s'", $h, $returned);
        }
    }
}

######################################################################
## nic_dnsmadeeasy_examples
######################################################################
sub nic_dnsmadeeasy_examples {
    return <<"EoEXAMPLE";
o 'dnsmadeeasy'

The 'dnsmadeeasy' protocol is used by the DNS Made Easy service at https://www.dnsmadeeasy.com.
API is documented here: https://dnsmadeeasy.com/technology/dynamic-dns/

Configuration variables applicable to the 'dnsmadeeasy' protocol are:
  protocol=dnsmadeeasy               ##
  login=email-address                ## Email address used to log in to your account.
  password=dynamic-record-password   ## Generated password for your dynamic DNS record.
  record-id-1,record-id-2,...        ## Numeric dynamic DNS record IDs, comma-separated if updating multiple.

Note: Dynamic record ID is generated when you create a new Dynamic DNS record in the DNS Made Easy control panel.

Example ${program}.conf file entries:
  ## single host update
  protocol=dnsmadeeasy,              \\
  username=dme\@example.com,         \\
  password=myg3nerat3dp4ssword,      \\
  1007,1008

EoEXAMPLE
}

######################################################################
## nic_dnsmadeeasy_update
######################################################################
sub nic_dnsmadeeasy_update {
    debug("\nnic_dnsmadeeasy_update -------------------");

    my %messages = (
        'error-auth' => 'Invalid username or password, or invalid IP syntax',
        'error-auth-suspend' => 'User has had their account suspended due to complaints or misuse of the service.',
        'error-auth-voided' => 'User has had their account permanently revoked.',
        'error-record-invalid' =>'Record ID number does not exist in the system.',
        'error-record-auth' => 'User does not have access to this record.',
        'error-record-ip-same' => 'No update required.',
        'error-system' => 'General system error which is caught and recognized by the system.',
        'error' => 'General system error unrecognized by the system.',
        'success' => 'Record successfully updated!',
    );

    ## update each configured host
    ## should improve to update in one pass
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("Setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "Updating %s", $h);

        # Set the URL that we're going to to update
        my $url;
        $url  = $globals{'ssl'} ? "https://" : "http://";
        $url .= $config{$h}{'server'} . $config{$h}{'script'};
        $url .= "?username=$config{$h}{'login'}";
        $url .= "&password=$config{$h}{'password'}";
        $url .= "&ip=$ip";
        $url .= "&id=$h";

        # Try to get URL
        my $reply = geturl(proxy => opt('proxy'), url => $url);

        # No response, declare as failed
        if (!defined($reply) || !$reply) {
            failed("Updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        next if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;
        my $returned = pop(@reply);
        if ($returned =~ 'success') {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("Updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            failed("Updating %s: Server said: '%s': %s", $h, $returned, $messages{$returned});
        }
    }
}

######################################################################
## nic_ovh_examples
######################################################################
sub nic_ovh_examples {
    return <<"EoEXAMPLE";

o 'ovh'

The 'ovh' protocol is used by DNS services offered by www.ovh.com.

API information and user instructions available at: https://docs.ovh.com/gb/en/domains/hosting_dynhost/

Configuration variables applicable to the 'ovh' protocol are:
  protocol=ovh                 ##
  login=dnsdomain-userid       ## The username/id registered with the service
  password=userid-password     ## The password related to the username/id
  fully.qualified.host         ## the hostiname registered with the service.

Example ${program}.conf file entries:
  ## single host update
  protocol=ovh,                   \\
  login=example.com-dynhostuser,  \\
  password=your_password,         \\
  test.example.com

EoEXAMPLE
}

######################################################################
## nic_ovh_update
######################################################################
sub nic_ovh_update {
    debug("\nnic_ovh_update -------------------");

    ## update each configured host
    ## should improve to update in one pass
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:","updating %s", $h);

        # Set the URL that we're going to update
        my $url;
        $url .= "https://$config{$h}{'server'}$config{$h}{'script'}?system=dyndns";
        $url .= "&hostname=$h";
        $url .= "&myip=";
        $url .= $ip if $ip;

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url,
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
        );

        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }

        my @reply = split /\n/, $reply;
        my $returned = List::Util::first { $_ =~ /good/ || $_ =~ /nochg/ } @reply;
        if ($returned) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            if ($returned =~ /good/) {
                success("updating %s: good: IP address set to %s", $h, $ip);
            } else {
                success("updating %s: skipped: IP address was already set to %s.", $h, $ip);
            }
        } else {
            $config{$h}{'status'} = 'failed';
            failed("updating %s: Server said: '%s'", $h, $reply);
        }
    }
}

######################################################################
## nic_porkbun_examples
######################################################################
sub nic_porkbun_examples {
    return <<"EoEXAMPLE";
o 'porkbun'

The 'porkbun' protocol is used for porkbun (https://porkbun.com/).
The API is documented here: https://porkbun.com/api/json/v3/documentation

Before setting up, it is necessary to create your API Key by referring to the following page.

https://kb.porkbun.com/article/190-getting-started-with-the-porkbun-api

Available configuration variables:
  * apikey (required): API Key of Porkbun API
  * secretapikey (required): Secret API Key of Porkbun API
  * on-root-domain=yes or no (default: no): Indicates whether the specified domain name (FQDN) is
    an unnamed record (Zone APEX) in a zone.
    It is useful to specify it as a local variable as shown in the example.
  * usev4, usev6 : These configuration variables can be specified as local variables to override
    the global settings. It is useful to finely control IPv4 or IPv6 as shown in the example.
  * use (deprecated) : This parameter is deprecated but can be overridden like the above parameters.

Limitations:
  * Multiple same name records (for round robin) are not supported.
    The same IP address is set for all, creating meaningless extra records.

Example ${program}.conf file entry:
  protocol=porkbun
  apikey=APIKey
  secretapikey=SecretAPIKey
  host.example.com,host2.sub.example.com
  on-root-domain=yes example.com,sub.example.com

Additional example to finely control IPv4 or IPv6 :
  # Example 01 : Global enable both IPv4 and IPv6, and update both records.
  usev4=webv4
  usev6=ifv6, ifv6=enp1s0

  protocol=porkbun
  apikey=APIKey
  secretapikey=SecretAPIKey
  host.example.com,host2.sub.example.com

  # Example 02 : Global enable only IPv4, and update only IPv6 record.
  usev4=webv4

  protocol=porkbun
  apikey=APIKey
  secretapikey=SecretAPIKey
  usev6=ifv6, ifv6=enp1s0, usev4=disabled ipv6.example.com
  
EoEXAMPLE
}

######################################################################
## nic_porkbun_update
######################################################################
sub nic_porkbun_update {
    debug("\nnic_porkbun_update -------------------");

    foreach my $host (@_) {
        foreach my $ipv ('ipv4', 'ipv6') {
            my $ip = delete $config{$host}{"want$ipv"};
            if (!$ip) {
                next;
            }
            my $rrset_type = is_ipv6($ip) ? "AAAA" : "A";

            my ($sub_domain, $domain);
            if ($config{$host}{'on-root-domain'}) {
                $sub_domain = '';
                $domain = $host;
            } else {
                ($sub_domain, $domain) = split(/\./, $host, 2);
            }
            info("setting %s address to %s for %s", $ipv, $ip, $host);
            verbose("UPDATE:","updating %s", $host);

            my $url = "https://porkbun.com/api/json/v3/dns/retrieveByNameType/$domain/$rrset_type/$sub_domain";
            my $data = encode_json({
                secretapikey => $config{$host}{'secretapikey'},
                apikey       => $config{$host}{'apikey'},
            });
            my $header = "Content-Type: application/json\n";
            my $reply = geturl(
                proxy     => opt('proxy'),
                url       => $url,
                headers   => $header,
                method    => 'POST',
                data      => $data,
            );
            # No response, declare as failed
            if (!defined($reply) || !$reply) {
                $config{$host}{"status-$ipv"} = "bad";
                failed("updating %s: Could not connect to porkbun.com.", $host);
                next;
            }
            if (!header_ok($host, $reply)) {
                $config{$host}{"status-$ipv"} = "bad";
                failed("updating %s: failed (%s)", $host, $reply);
                next;
            }
            # Strip header
            # Porkbun sends data in chunks, so it is assumed to be one chunk and parsed forcibly.
            $reply =~ qr/{(?:[^{}]*|(?R))*}/mp;
            my $response = eval { decode_json(${^MATCH}) };
            if (!defined($response)) {
                $config{$host}{"status-$ipv"} = "bad";
                failed("%s -- Unexpected service response.", $host);
                next;
            }
            if ($response->{status} ne 'SUCCESS') {
                $config{$host}{"status-$ipv"} = "bad";
                failed("%s -- Unexpected status. (status = %s)", $host, $response->{status});
                next;
            }
            my $records = $response->{records};
            if (ref($records) eq 'ARRAY' && defined $records->[0]->{'id'}) {
                my $count = scalar(@{$records});
                if ($count > 1) {
                    warning("updating %s: There are multiple applicable records. Only first record is used. Overwrite all with the same content.");
                }
                my $current_content = $records->[0]->{'content'};
                if ($current_content eq $ip) {
                    $config{$host}{"status-$ipv"} = "good";
                    success("updating %s: skipped: %s address was already set to %s.", $ipv, $host, $ip);
                    next;
                }
                my $ttl = $records->[0]->{'ttl'};
                my $notes = $records->[0]->{'notes'};
                debug("ttl = %s", $ttl);
                debug("notes = %s", $notes);
                $url = "https://porkbun.com/api/json/v3/dns/editByNameType/$domain/$rrset_type/$sub_domain";
                $data = encode_json({
                    secretapikey => $config{$host}{'secretapikey'},
                    apikey       => $config{$host}{'apikey'},
                    content      => $ip,
                    ttl          => $ttl,
                    notes        => $notes,
                });
                $reply = geturl(
                    proxy     => opt('proxy'),
                    url       => $url,
                    headers   => $header,
                    method    => 'POST',
                    data      => $data,
                );
                # No response, declare as failed
                if (!defined($reply) || !$reply) {
                    failed("updating %s: Could not connect to porkbun.com.", $host);
                    next;
                }
                if (!header_ok($host, $reply)) {
                    failed("updating %s: failed (%s)", $host, $reply);
                    next;
                }
                $config{$host}{"status-$ipv"} = "good";
                success("updating %s: good: %s address set to %s", $ipv, $host, $ip);
                next;
            } else {
                $config{$host}{"status-$ipv"} = "bad";
                failed("updating %s: No applicable existing records.", $host);
                next;
            }
        }
    }
}

sub nic_cloudns_examples {
    return <<"EoEXAMPLE";
o 'cloudns'

The 'cloudns' protocol is used for ClouDNS (https://www.cloudns.net).  Details
about dynamic DNS updates can be found at https://www.cloudns.net/dynamic-dns/.

Available configuration variables:
  * dynurl: The DynURL associated with the A or AAAA record you wish to update.

Limitations:
  * $program cannot tell if the DynURL you provide belongs to the hostname you
    specify.
  * ClouDNS does not document how to tell whether an update suceeded or failed,
    so there is no way for $program to reliably handle failures.
  * The ClouDNS API does not provide a reliable way to set the desired IP
    address. It might save the IP address you want, or it might save the IP
    address that connects to CloudDNS. It is more likely to work if you do not
    use a proxy.

Example ${program}.conf file entry:
  protocol=cloudns,                                                        \\
  dynurl=https://ipv4.cloudns.net/api/dynamicURL/?q=Njc1OTE2OjY3Njk0ND..., \\
  myhost.example.com
EoEXAMPLE
}

sub nic_cloudns_update {
    my %groups = group_hosts_by([ @_ ], [ qw(dynurl) ]);
    for my $hr (values(%groups)) {
        my @hosts = @$hr;
        my $hosts = join(',', @hosts);
        my $ip = $config{$hosts[0]}{'wantip'};
        my $dynurl = $config{$hosts[0]}{'dynurl'};
        delete $config{$_}{'wantip'} for @hosts;
        # https://www.cloudns.net/wiki/article/36/ says, "If you are behind a proxy and your real
        # IP is set in the header X-Forwarded-For you need to add &proxy=1 at the end of the
        # DynamicURL." We abuse this to pass the desired IP address to ClouDNS, which might not be
        # the same as the client IP address seen by ClouDNS.
        my $reply = geturl(
            proxy => opt('proxy'),
            url => $dynurl . '&proxy=1',
            headers => "X-Forwarded-For: $ip\n",
        );
        if (($reply // '') eq '' || !header_ok($hosts, $reply)) {
            $config{$_}{'status'} = 'failed' for @hosts;
            failed("updating %s: failed to visit DynURL", $hosts);
            next;
        }
        $reply =~ s/^.*?\n\n//s;  # Strip the headers.
        chomp($reply);
        if ($reply eq "The record's key is wrong!" || $reply eq "Invalid request.") {
            $config{$_}{'status'} = 'failed' for @hosts;
            failed("updating %s: %s", $hosts, $reply);
            next;
        }
        # There's no documentation explaining possible return values, so we assume success.
        $config{$_}{'ip'} = $ip for @hosts;
        $config{$_}{'mtime'} = $now for @hosts;
        $config{$_}{'status'} = 'good' for @hosts;
        success("updating %s: IP address set to %s", $hosts, $ip);
    }
}

######################################################################
## nic_dinahosting_examples
######################################################################
sub nic_dinahosting_examples {
    return <<"EoEXAMPLE";
o 'dinahosting'

The 'dinahosting' protocol is used by dinahosting (https://dinahosting.com).
Details about the API can be found at https://dinahosting.com/api.

Available configuration variables and their defaults:
  * login (required) is your username.
  * password (required) is your password.
  * server=dinahosting.com is the hostname part of the dinahosting API URL.
  * script=/special/api.php is the path part of the dinahosting API URL.

Example ${program}.conf file entry:
  protocol=dinahosting,  \\
  login=myusername,      \\
  password=mypassword    \\
  myhost.mydomain.com
EoEXAMPLE
}

######################################################################
## nic_dinahosting_update
######################################################################
sub nic_dinahosting_update {
    debug("\nnic_dinahosting_update -------------------");
    for my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:", "updating %s", $h);
        my ($hostname, $domain) = split(/\./, $h, 2);
        my $url = "https://$config{$h}{'server'}$config{$h}{'script'}";
        $url .= "?hostname=$hostname";
        $url .= "&domain=$domain";
        $url .= "&command=Domain_Zone_UpdateType" . is_ipv6($ip) ? 'AAAA' : 'A';
        $url .= "&ip=$ip";
        my $reply = geturl(
            proxy => opt('proxy'),
            login => $config{$h}{'login'},
            password => $config{$h}{'password'},
            url => $url,
        );
        $config{$h}{'status'} = 'failed';  # assume failure until otherwise determined
        if (!$reply) {
            failed("updating %s: failed to visit URL %s", $h, $url);
            next;
        }
        next if !header_ok($h, $reply);
        $reply =~ s/^.*?\n\n//s;  # Strip the headers.
        if ($reply !~ /Success/i) {
            $reply =~ /^responseCode = (\d+)$/m;
            my $code = $1 // '<undefined>';
            $reply =~ /^errors_0_message = '(.*)'$/m;
            my $message = $1 // '<undefined>';
            failed("updating %s: error %d: %s", $code, $message);
            next;
        }
        $config{$h}{'ip'}     = $ip;
        $config{$h}{'mtime'}  = $now;
        $config{$h}{'status'} = 'good';
        success("updating %s: IP address set to %s", $h, $ip);
    }
}

######################################################################
## nic_gandi_examples
## by Jimmy Thrasibule <dev@jimmy.lt>
######################################################################
sub nic_gandi_examples {
    return <<"EoEXAMPLE";
o 'gandi'

The 'gandi' protocol is used by the LiveDNS service offered by gandi.net.
Description of Gandi's LiveDNS API can be found at:

    https://api.gandi.net/docs/livedns/

Available configuration variables:
  * password: The Gandi API key. If you don’t have one yet, you can generate
    your production API key from the API Key Page (in the Security section).
    Required.
  * zone: The DNS zone to be updated. Required.
  * ttl: The time-to-live value associated with the updated DNS record.
    Optional; uses Gandi's default (3h) if unset.

Example ${program}.conf file entries:
  ## Single host update.
  protocol=gandi,                           \\
  zone=example.com,                         \\
  password=my-gandi-api-key,                \\
  host.example.com

  ## Multiple host update.
  protocol=gandi,                           \\
  zone=example.com,                         \\
  password=my-gandi-api-key,                \\
  ttl=1h                                    \\
  hosta.example.com,hostb.sub.example.com
EoEXAMPLE
}

######################################################################
## nic_gandi_update
######################################################################
sub nic_gandi_update {
    debug("\nnic_gandi_update -------------------");

    # Update each set configured host.
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        (my $hostname = $h) =~ s/\.\Q$config{$h}{zone}\E$//;

        info("%s -- Setting IP address to %s.", $h, $ip);
        verbose("UPDATE:", "updating %s", $h);

        my $headers;
        $headers  = "Content-Type: application/json\n";
        $headers .= "Authorization: Apikey $config{$h}{'password'}\n";

        my $data = encode_json({
            defined($config{$h}{'ttl'}) ? (rrset_ttl => $config{$h}{'ttl'}) : (),
            rrset_values => [$ip],
        });

        my $rrset_type = is_ipv6($ip) ? "AAAA" : "A";
        my $url;
        $url  = "https://$config{$h}{'server'}$config{$h}{'script'}";
        $url .= "/livedns/domains/$config{$h}{'zone'}/records/$hostname/$rrset_type";

        my $reply = geturl(
            proxy    => opt('proxy'),
            url      => $url,
            headers  => $headers,
            method   => 'PUT',
            data     => $data,
        );
        unless ($reply) {
            failed("%s -- Could not connect to %s.", $h, $config{$h}{'server'});
            next;
        }
        my $ok = header_ok($h, $reply);

        $reply =~ s/^.*?\n\n//s;
        my $response = eval { decode_json($reply) };
        if (!defined($response)) {
            $config{$h}{'status'} = "bad";

            failed("%s -- Unexpected service response.", $h);
            next;
        }

        if ($ok) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = "good";

            success("%s -- Updated successfully to %s.", $h, $ip);
        } else {
            $config{$h}{'status'} = "bad";

            if (defined($response->{status}) && $response->{status} eq "error") {
                my @errors;
                for my $err (@{$response->{errors}}) {
                    push(@errors, $err->{description});
                }
                failed("%s -- %s.", $h, join(", ", @errors));
            } else {
                failed("%s -- Unexpected service response.", $h);
            }
        }
    }
}
######################################################################
## nic_keysystems_examples
######################################################################
sub nic_keysystems_examples {
    return <<EoEXAMPLE;
o 'keysystems'

The 'keysystems' protocol is used by the non-free
dynamic DNS service offered by www.domaindiscount24.com and www.rrpproxy.net.
Check https://www.domaindiscount24.com/faq/en/dynamic-dns for API

Configuration variables applicable to the 'keysystems' protocol are:
protocol=keysystems
server=dynamicdns.key-systems.net
password=service-password          ## password (token) registered with the service
subdomain.example.com              ## the host registered with the service.

Example ${program}.conf file entries:
## single host update
protocol=keysystems,             \\\\
password=service-password        \\\\
example.com

EoEXAMPLE
}

######################################################################
## nic_keysystems_update
## response contains "code 200" on succesfull completion
######################################################################
sub nic_keysystems_update {
 debug("\nnic_keysystems_update -------------------");

 ## update each configured host
 ## should improve to update in one pass
 foreach my $h (@_) {
   my $ip = delete $config{$h}{'wantip'};
   info("KEYSYSTEMS setting IP address to %s for %s", $ip, $h);

   my $url = "http://$config{$h}{'server'}/update.php?hostname=$h&password=$config{$h}{'password'}&ip=$ip";

   # Try to get URL
   my $reply = geturl(opt('proxy'), $url);

   # No response, declare as failed
   if (!defined($reply) || !$reply) {
     failed("KEYSYSTEMS updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
     last;
   }
   last if !header_ok($h, $reply);

   if ($reply =~ /code = 200/)
   {
       $config{$h}{'ip'}   = $ip;
       $config{$h}{'mtime'} = $now;
       $config{$h}{'status'} = 'good';
       success("updating %s: good: IP address set to %s", $h, $ip);
    }
    else
    {
       $config{$h}{'status'} = 'failed';
       failed("updating %s: Server said: '$reply'", $h);
    }
  }
}

######################################################################
## nic_regfishde_examples
######################################################################
sub nic_regfishde_examples {
    return <<EoEXAMPLE;
o 'regfishde'
The 'regfishde' protocol is used by the non-free dynamic DNS service offered by www.regfish.de.
Check https://www.regfish.de for configuration variables applicable to the 'regfishde' protocol:
protocol=regfishde
server=dyndns.regfish.de
password=service-password          ## password (token) registered with the service
myhost.mydomain.com                ## the host registered with the service.
Example ${program}.conf file entries:
## single host update
protocol=regfishde
password=service-password
myhost.mydomain.com
EoEXAMPLE
}

######################################################################
## nic_regfishde_update
## response contains "success" on succesfull completion
######################################################################
sub nic_regfishde_update {
 debug("\nnic_regfishde_update -------------------");

 ## update configured host
 for my $h (@_) {
   my $ip = delete $config{$h}{'wantip'};
   my $ipv6 = delete $config{$h}{'wantip'};
   
   info("regfish.de setting IP address to %s for %s", $ip, $h);

   my $ipv = ($ip eq ($ipv6 // '')) ? '6' : '4';
   my $url = "https://$config{$h}{'server'}/?fqdn=$h&ipv$ipv=$ip&forcehost=1&token=$config{$h}{'password'}";

   # Try to get URL
   my $reply = geturl(proxy => opt('proxy'), url => $url);

   # No response, give error
   if (!defined($reply) || !$reply) {
     failed("regfish.de updating %s: failed: %s.", $h, $config{$h}{'server'});
     last;
   }
   last if !header_ok($h, $reply);

   if ($reply =~ /success/)
   {
       $config{$h}{'ip'} = $ip;
       $config{$h}{'mtime'} = $now;
       $config{$h}{'status'} = 'good';
       success("updating %s: good: IP address set to %s", $h, $ip);
    }
    else
    {
       $config{$h}{'status'} = 'failed';
       failed("updating %s: Server said: '$reply'", $h);
    }
  }
}

######################################################################
######################################################################
## enom
######################################################################
sub nic_enom_examples {
    return <<EoEXAMPLE;
o 'enom'
The 'enom' protocol is used by DNS services offered by www.enom.com and their resellers.
Configuration variables applicable to the 'enom' protocol are:
  protocol=enom                ## 
  server=fqdn.of.service       ## defaults to dynamic.name-services.com
  login=domain.name            ## base domain name
  password=domain-password     ## the domain password registered with the service
  A_record                     ## the A record(s) registered with the service
Example ${program}.conf file entries:
  ## single host update
  protocol=enom,                                   \\
  login=mydomain.com,                              \\
  password=mydomain.com-password                   \\
  www
  ## multiple host update
  protocol=enom,                                   \\
  login=mydomain.com,                              \\
  password=mydomain.com-password                   \\
  www,mail,*
EoEXAMPLE
}
######################################################################
## enom_update
##
## written by Lars Fredriksson
## modified by Leonidas Arvanitis
##
## based on http://www.edoceo.com/creo/enomddu.php
##
## needs this url to update:
##   http://dynamic.name-services.com/interface.asp?Command=SetDNSHost&HostName=www
##   &Zone=mydomain.com&DomainPassword=MyD0mainPa55w0rD&Address=123.45.678.90
##
######################################################################
sub nic_enom_update {
    debug("\nenom_update -------------------");
    ## update each configured host
    foreach my $h (@_) {
        my $ip = delete $config{$h}{'wantip'};
        info("setting IP address to %s for %s", $ip, $h);
        verbose("UPDATE:","updating %s", $h);

        my $url;
        $url   = "https://$config{$h}{'server'}/interface.asp?Command=SetDNSHost";
        $url  .= "&HostName=$h";
        $url  .= "&Zone=$config{$h}{'login'}";
        $url  .= "&DomainPassword=$config{$h}{'password'}";
        $url  .= "&Address=";
        $url  .= $ip if $ip;

        my $reply = geturl(
            proxy => opt('proxy'),
            url => $url
        );

        if (!defined($reply) || !$reply) {
            failed("updating %s: Could not connect to %s.", $h, $config{$h}{'server'});
            last;
        }

        last if !header_ok($h, $reply);

        my @reply = split /\n/, $reply;

        if (grep /Done=true/i, @reply) {
            $config{$h}{'ip'}     = $ip;
            $config{$h}{'mtime'}  = $now;
            $config{$h}{'status'} = 'good';
            success("updating %s: good: IP address set to %s", $h, $ip);
        } else {
            $config{$h}{'status'} = 'failed';
            warning("SENT:    %s", $url) unless opt('verbose');
            warning("REPLIED: %s", $reply);
            failed("updating %s: Invalid reply.", $h);
        }
    }
}

sub nic_digitalocean_examples {
    return <<"EoEXAMPLE";
o 'digitalocean'

The 'digitalocean' protocol updates domains hosted by Digital Ocean (https://www.digitalocean.com/).

This protocol supports both IPv4 and IPv6. It will only update an existing record; it will not
create a new one. So, before using it, make sure there's already one (and at most one) of each
record type (A and/or AAAA) you plan to update present in your Digital Ocean zone.

This protocol implements the API documented here:
  https://docs.digitalocean.com/reference/api/api-reference/.

You can get your API token by following these instructions:
  https://docs.digitalocean.com/reference/api/create-personal-access-token/

Available configuration variables:
  * server (optional): API server. Defaults to 'api.digitalocean.com'.
  * zone (required): DNS zone under which the hostname falls.
  * password (required): API token from DigitalOcean Control Panel. See instructions linked above.

Example ${program}.conf file entries:
  protocol=digitalocean, \\
  zone=example.com,      \\
  password=api-token     \\
  example.com,sub.example.com
EoEXAMPLE
}

sub nic_digitalocean_update_one {
    my ($h, $ip, $ipv) = @_;

    info("setting %s address to %s for %s", $ipv, $ip, $h);

    my $server = $config{$h}{'server'};
    my $type = $ipv eq 'ipv6' ? 'AAAA' : 'A';

    my $headers;
    $headers  = "Content-Type: application/json\n";
    $headers .= "Authorization: Bearer $config{$h}{'password'}\n";

    my $list_url;
    $list_url  = "https://$server/v2/domains/$config{$h}{'zone'}/records";
    $list_url .= "?name=$h";
    $list_url .= "&type=$type";

    my $list_resp = geturl(
        proxy => opt('proxy'),
        url => $list_url,
        headers => $headers,
    );
    unless ($list_resp && header_ok($h, $list_resp)) {
        $config{$h}{"status-$ipv"} = 'failed';
        failed("listing %s %s: Failed connection or bad response from %s.", $h, $ipv, $server);
        return;
    }
    $list_resp =~ s/^.*?\n\n//s;  # Strip header

    my $list = eval { decode_json($list_resp) };
    if ($@) {
        $config{$h}{"status-$ipv"} = 'failed';
        failed("listing %s %s: JSON decoding failure", $h, $ipv);
        return;
    }

    my $elem = $list;
    unless ((ref($elem) eq 'HASH') &&
            (ref ($elem = $elem->{'domain_records'}) eq 'ARRAY') &&
            (@$elem == 1 && ref ($elem = $elem->[0]) eq 'HASH')) {
        $config{$h}{"status-$ipv"} = 'failed';
        failed("listing %s %s: no record, multiple records, or malformed JSON", $h, $ipv);
        return;
    }

    my $current_ip = $elem->{'data'};
    my $record_id = $elem->{'id'};

    if ($current_ip eq $ip) {
        info("updating %s %s: IP is already %s, no update needed.", $h, $ipv, $ip);
    } else {
        my $update_data = encode_json({'type' => $type, 'data' => $ip});
        my $update_resp = geturl(
            proxy => opt('proxy'),
            url => "https://$server/v2/domains/$config{$h}{'zone'}/records/$record_id",
            method => 'PATCH',
            headers => $headers,
            data => $update_data,
        );
        unless ($update_resp && header_ok($h, $update_resp)) {
            $config{$h}{"status-$ipv"} = 'failed';
            failed("updating %s %s: Failed connection or bad response from %s.", $h, $ipv, $server);
            return;
        }
    }

    $config{$h}{"status-$ipv"} = 'good';
    $config{$h}{"ip-$ipv"}     = $ip;
    $config{$h}{"mtime"}       = $now;
}

sub nic_digitalocean_update {
    debug("\nnic_digitalocean_update -------------------");

    foreach my $h (@_) {
        my $ipv4 = delete $config{$h}{'wantipv4'};
        my $ipv6 = delete $config{$h}{'wantipv6'};

        if ($ipv4) {
            nic_digitalocean_update_one($h, $ipv4, 'ipv4');
        }

        if ($ipv6) {
            nic_digitalocean_update_one($h, $ipv6, 'ipv6');
        }
    }
}

######################################################################
## nic_infomaniak_examples
######################################################################
sub nic_infomaniak_examples {
    return <<"EoEXAMPLE";

o 'infomaniak'

The 'infomaniak' protocol is used by DNS services offered by www.infomaniak.com.

Configuration variables applicable to the 'infomaniak' protocol are:
  protocol=infomaniak
  login=ddns_username          ## the DDNS username set up in Infomaniak
  password=ddns_password       ## the DDNS username set up in Infomaniak
  example.com                  ## domain name to update

Example ${program}.conf file entries:
  protocol=infomaniak,       \\
  login=my-username,         \\
  password=my-password       \\
  my.address.com

For more information about how to create a dynamic DNS, see https://faq.infomaniak.com/2357.

EoEXAMPLE
}

######################################################################
## nic_infomaniak_update
##
## written by Timothée Andres
##
## based on https://faq.infomaniak.com/2376
##
## needs one of the following urls to update:
##   https://username:password@infomaniak.com/nic/update?hostname=subdomain.yourdomain.com&myip=1.2.3.4
##   https://infomaniak.com/nic/update?hostname=subdomain.yourdomain.com&myip=1.2.3.4&username=XXX&password=XXX
######################################################################
sub nic_infomaniak_update {
    debug("\nnic_infomaniak_update -------------------");

    foreach my $h (@_) {
        INFOMANIAK_IP_LOOP:
        foreach my $v (4, 6) {
            my $ip = delete $config{$h}{"wantipv$v"};

            if (!defined $ip) {
                debug("ipv%d not wanted, skipping", $v);
                next;
            }

            verbose("setting IP address to %s for %s", $ip, $h);
            info("updating %s", $h);

            # No change in IP => nochg <w.x.y.z>
            # Bad auth => badauth
            # Bad domain name => nohost
            # Bad IP => nohost
            # IP changed => good <xxxx::yyyy>
            # No domain name => Validation failed
            my %statuses = (
                'good'    => (1, sprintf("IP set to %s for %s", $ip, $h)),
                'nochg'   => (1, sprintf("IP already set to %s for %s", $ip, $h)),
                'nohost'  => (0, sprintf("Bad domain name %s or bad IP %s", $h, $ip)),
                'badauth' => (0, sprintf("Bad authentication for %s", $h)),
            );

            my $url1 = "https://$config{$h}{'login'}:$config{$h}{'password'}";
            $url1 .= "\@infomaniak.com/nic/update";
            $url1 .= "?hostname=$h";
            $url1 .= "&myip=$ip";

            my $url2 = "https://infomaniak.com/nic/update";
            $url2 .= "?hostname=$h";
            $url2 .= "&myip=$ip";
            $url2 .= "&username=$config{$h}{'login'}";
            $url2 .= "&password=$config{$h}{'password'}";

            my $reply;

            foreach my $url ($url1, $url2) {
                verbose("trying update with %s", $url);
                $reply = geturl(proxy => opt('proxy'), url => $url);
                if (!defined($reply) || !$reply) {
                    info("could not update %s using url %s, trying next one", $h, $url);
                    next;
                }

                my ($status) = split / /, $reply, 1;
                my ($updated, $msg) =
                    $statuses{$status} // (0, sprintf("Unknown reply from Infomaniak: %s", $reply));

                if (defined $updated && $updated) {
                    info($msg);
                    $config{$h}{"ipv$v"} = $ip;
                    $config{$h}{'mtime'} = $config{$h}{'mtime'} // $now;
                    $config{$h}{'status'} = 'good';
                    $config{$h}{"status-ipv$v"} = 'good';
                    next INFOMANIAK_IP_LOOP;
                }
                else {
                    warning($msg);
                }
            }

            $config{$h}{'status'} = $config{$h}{'status'} // 'failed';
            $config{$h}{"status-ipv$v"} = 'failed';
            failed("updating %s: could not update IP on Infomaniak", $h);
        }
    }
}

# Execute main() if this file is run as a script or run via PAR (https://metacpan.org/pod/PAR),
# otherwise do nothing. This "modulino" pattern makes it possible to import this file as a module
# and test its functions directly; there's no need for test-only command-line arguments or stdout
# parsing.
__PACKAGE__->main() unless caller() && caller() ne 'PAR';

######################################################################
## Emacs and Vim settings

# Local Variables:
# mode: perl
# fill-column: 99
# indent-tabs-mode: nil
# perl-indent-level: 4
# tab-width: 8
# End:

# vim: ai et ts=8 sw=4 tw=99 cc=+1 filetype=perl

__END__