File: ipvsadm.c

package info (click to toggle)
ipvsadm 1:1.31-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 496 kB
  • sloc: ansic: 4,070; sh: 288; makefile: 135
file content (2355 lines) | stat: -rw-r--r-- 67,370 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
/*
 *      ipvsadm - IP Virtual Server ADMinistration program
 *                for IPVS NetFilter Module in kernel 2.4
 *
 *      Version: $Id$
 *
 *      Authors: Wensong Zhang <wensong@linuxvirtualserver.org>
 *               Peter Kese <peter.kese@ijs.si>
 *
 *      This program is based on ippfvsadm.
 *
 *      Changes:
 *        Wensong Zhang       :   added the editting service & destination support
 *        Wensong Zhang       :   added the feature to specify persistent port
 *        Jacob Rief          :   found the bug that masquerading dest of
 *                                different vport and dport cannot be deleted.
 *        Wensong Zhang       :   fixed it and changed some cosmetic things
 *        Wensong Zhang       :   added the timeout setting for persistent service
 *        Wensong Zhang       :   added specifying the dest weight zero
 *        Wensong Zhang       :   fixed the -E and -e options
 *        Wensong Zhang       :   added the long options
 *        Wensong Zhang       :   added the hostname and portname input
 *        Wensong Zhang       :   added the hostname and portname output
 *	  Lars Marowsky-Br´┐Że  :   added persistence granularity support
 *        Julian Anastasov    :   fixed the (null) print for unknown services
 *        Wensong Zhang       :   added the port_to_anyname function
 *        Horms               :   added option to read commands from stdin
 *        Horms               :   modified usage function so it prints to
 *                            :   stdout if an exit value of 0 is used and
 *                            :   stdout otherwise. Program is then terminated
 *                            :   with the supplied exit value.
 *        Horms               :   updated manpage and usage funtion so
 *                            :   the reflect the options available
 *        Wensong Zhang       :   added option to write rules to stdout
 *        Horms               :   added ability to specify a fwmark
 *                            :   instead of a server and port for
 *                            :   a virtual service
 *        Horms               :   tightened up checking of services
 *                            :   in parse_service
 *        Horms               :   ensure that a -r is passed when needed
 *        Wensong Zhang       :   fixed the output of fwmark rules
 *        Horms               :   added kernel version verification
 *        Horms               :   Specifying command and option options
 *                                (e.g. -Ln or -At) in one short option
 *                                with popt problem fixed.
 *        Wensong Zhang       :   split the process_options and make
 *                                two versions of parse_options.
 *        Horms               :   attempting to save or restore when
 *                                compiled against getopt_long now results
 *                                in an informative error message rather
 *                                than the usage information
 *        Horms               :   added -v option
 *        Wensong Zhang       :   rewrite most code of parsing options and
 *                                processing options.
 *        Alexandre Cassen    :   added ipvs_syncd SyncdID support to filter
 *                                incoming sync messages.
 *        Guy Waugh & Ratz    :   added --exact option and spelling cleanup
 *        vbusam@google.com   :   added IPv6 support
 *
 *
 *      ippfvsadm - Port Fowarding & Virtual Server ADMinistration program
 *
 *      Copyright (c) 1998 Wensong Zhang
 *      All rights reserved.
 *
 *      Author: Wensong Zhang <wensong@iinchina.net>
 *
 *      This ippfvsadm is derived from Steven Clarke's ipportfw program.
 *
 *      portfw - Port Forwarding Table Editing v1.1
 *
 *      Copyright (c) 1997 Steven Clarke
 *      All rights reserved.
 *
 *      Author: Steven Clarke <steven@monmouth.demon.co.uk>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#undef __KERNEL__	/* Makefile lazyness ;) */
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <stdarg.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/wait.h>           /* For waitpid */
#include <arpa/inet.h>

#include <net/if.h>
#include <netinet/ip_icmp.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>

#include "popt.h"
#define IPVS_OPTION_PROCESSING	"popt"

#include "config_stream.h"
#include "libipvs/libipvs.h"

#define IPVSADM_VERSION_NO	"v" VERSION
#define IPVSADM_VERSION_DATE	"2019/12/24"
#define IPVSADM_VERSION		IPVSADM_VERSION_NO " " IPVSADM_VERSION_DATE

#define MAX_TIMEOUT		(86400*31)	/* 31 days */

#define CMD_NONE		0
#define CMD_ADD			(CMD_NONE+1)
#define CMD_EDIT		(CMD_NONE+2)
#define CMD_DEL			(CMD_NONE+3)
#define CMD_FLUSH		(CMD_NONE+4)
#define CMD_LIST		(CMD_NONE+5)
#define CMD_ADDDEST		(CMD_NONE+6)
#define CMD_DELDEST		(CMD_NONE+7)
#define CMD_EDITDEST		(CMD_NONE+8)
#define CMD_TIMEOUT		(CMD_NONE+9)
#define CMD_STARTDAEMON		(CMD_NONE+10)
#define CMD_STOPDAEMON		(CMD_NONE+11)
#define CMD_RESTORE		(CMD_NONE+12)
#define CMD_SAVE		(CMD_NONE+13)
#define CMD_ZERO		(CMD_NONE+14)
#define CMD_MAX			CMD_ZERO
#define NUMBER_OF_CMD		(CMD_MAX - CMD_NONE)

static const char* cmdnames[] = {
	"add-service",
	"edit-service",
	"delete-service",
	"flush",
	"list",
	"add-server",
	"delete-server",
	"edit-server",
	"set",
	"start-daemon",
	"stop-daemon",
	"restore",
	"save",
	"zero",
};

#define OPT_NONE		0x000000
#define OPT_NUMERIC		0x000001
#define OPT_CONNECTION		0x000002
#define OPT_SERVICE		0x000004
#define OPT_SCHEDULER		0x000008
#define OPT_PERSISTENT		0x000010
#define OPT_NETMASK		0x000020
#define OPT_SERVER		0x000040
#define OPT_FORWARD		0x000080
#define OPT_WEIGHT		0x000100
#define OPT_UTHRESHOLD		0x000200
#define OPT_LTHRESHOLD		0x000400
#define OPT_MCAST		0x000800
#define OPT_TIMEOUT		0x001000
#define OPT_DAEMON		0x002000
#define OPT_STATS		0x004000
#define OPT_RATE		0x008000
#define OPT_THRESHOLDS		0x010000
#define OPT_PERSISTENTCONN	0x020000
#define OPT_NOSORT		0x040000
#define OPT_SYNCID		0x080000
#define OPT_EXACT		0x100000
#define OPT_ONEPACKET		0x200000
#define OPT_PERSISTENCE_ENGINE  0x400000
#define OPT_SCHED_FLAGS		0x800000
#define OPT_MCAST_GROUP		0x01000000
#define OPT_MCAST_PORT		0x02000000
#define OPT_MCAST_TTL		0x04000000
#define OPT_SYNC_MAXLEN	0x08000000
#define OPT_TUN_INFO		0x10000000
#define OPT_TUN_TYPE		0x20000000
#define OPT_TUN_PORT		0x40000000
#define OPT_TUN_NOCSUM		0x80000000
#define OPT_TUN_CSUM		0x100000000
#define OPT_TUN_REMCSUM		0x200000000
#define NUMBER_OF_OPT		34

#define OPTC_NUMERIC		0
#define OPTC_CONNECTION		1
#define OPTC_SERVICE		2
#define OPTC_SCHEDULER		3
#define OPTC_PERSISTENT		4
#define OPTC_NETMASK		5
#define OPTC_SERVER		6
#define OPTC_FORWARD		7
#define OPTC_WEIGHT		8
#define OPTC_UTHRESHOLD		9
#define OPTC_LTHRESHOLD		10
#define OPTC_MCAST		11
#define OPTC_TIMEOUT		12
#define OPTC_DAEMON		13
#define OPTC_STATS		14
#define OPTC_RATE		15
#define OPTC_THRESHOLDS		16
#define OPTC_PERSISTENTCONN	17
#define OPTC_NOSORT		18
#define OPTC_SYNCID		19
#define OPTC_EXACT		20
#define OPTC_ONEPACKET		21
#define OPTC_PERSISTENCE_ENGINE	22
#define OPTC_SCHED_FLAGS	23
#define OPTC_MCAST_GROUP	24
#define OPTC_MCAST_PORT		25
#define OPTC_MCAST_TTL		26
#define OPTC_SYNC_MAXLEN	27
#define OPTC_TUN_INFO		28
#define OPTC_TUN_TYPE		29
#define OPTC_TUN_PORT		30
#define OPTC_TUN_NOCSUM		31
#define OPTC_TUN_CSUM		32
#define OPTC_TUN_REMCSUM	33

static const char* optnames[] = {
	"numeric",
	"connection",
	"service-address",
	"scheduler",
	"persistent",
	"netmask",
	"real-server",
	"forwarding-method",
	"weight",
	"u-threshold",
	"l-threshold",
	"mcast-interface",
	"timeout",
	"daemon",
	"stats",
	"rate",
	"thresholds",
	"persistent-conn",
	"nosort",
	"syncid",
	"exact",
	"ops",
	"pe",
	"sched-flags",
	"mcast-group",
	"mcast-port",
	"mcast-ttl",
	"sync-maxlen",
	"tun-info",
	"tun-type",
	"tun-port",
	"tun-nocsum",
	"tun-csum",
	"tun-remcsum",
};

/*
 * Table of legal combinations of commands and options.
 * Key:
 *  '+'  compulsory
 *  'x'  illegal
 *  '1'  exclusive (only one '1' option can be supplied)
 *  ' '  optional
 */
static const char commands_v_options[NUMBER_OF_CMD][NUMBER_OF_OPT] =
{
	/*   -n   -c   svc  -s   -p   -M   -r   fwd  -w   -x   -y   -mc  tot  dmn  -st  -rt  thr  -pc  srt  sid  -ex  ops  -pe  -b   grp  port ttl  size tinf type tprt nocs csum remc */
/*ADD*/     {'x', 'x', '+', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*EDIT*/    {'x', 'x', '+', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*DEL*/     {'x', 'x', '+', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*FLUSH*/   {'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*LIST*/    {' ', '1', '1', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', '1', '1', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', 'x', 'x', 'x', 'x', 'x'},
/*ADDSRV*/  {'x', 'x', '+', 'x', 'x', 'x', '+', ' ', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', ' ', ' ', ' ', ' '},
/*DELSRV*/  {'x', 'x', '+', 'x', 'x', 'x', '+', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*EDITSRV*/ {'x', 'x', '+', 'x', 'x', 'x', '+', ' ', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', ' ', ' ', ' ', ' '},
/*TIMEOUT*/ {'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*STARTD*/  {'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', 'x', 'x', 'x', 'x', ' ', ' ', ' ', ' ', 'x', 'x', 'x', 'x', 'x', 'x'},
/*STOPD*/   {'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*RESTORE*/ {'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*SAVE*/    {' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
/*ZERO*/    {'x', 'x', ' ', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'},
};

static const char * const tunnames[] = {
	"ipip",
	"gue",
	"gre",
};

static const char * const tunflags[] = {
	"-c",		/* without checksum */
	"+c",		/* with checksum */
	"r+c",		/* with remote checksum */
};

static const char * const tun_flags_opts[] = {
	"--tun-nocsum",
	"--tun-csum",
	"--tun-remcsum",
};

static const int tunopts[] = {
	OPTC_TUN_PORT,
	OPTC_TUN_NOCSUM,
	OPTC_TUN_CSUM,
	OPTC_TUN_REMCSUM,
};

#define NUMBER_OF_TUN_OPT		4
#define NA				"n/a"

/*
 * Table of legal combinations of tunnel types and options.
 * Key:
 *  '+'  compulsory
 *  'x'  illegal
 *  '1'  exclusive (only one '1' option can be supplied)
 *  ' '  optional
 */
static const char
tunnel_types_v_options[IP_VS_CONN_F_TUNNEL_TYPE_MAX][NUMBER_OF_TUN_OPT] = {
	/*  tprt nocs csum remc */
/* ipip */ {'x', 'x', 'x', 'x'},
/* gue */  {'+', '1', '1', '1'},
/* gre */  {'x', '1', '1', 'x'},
};

/* printing format flags */
#define FMT_NONE		0x0000
#define FMT_NUMERIC		0x0001
#define FMT_RULE		0x0002
#define FMT_STATS		0x0004
#define FMT_RATE		0x0008
#define FMT_THRESHOLDS		0x0010
#define FMT_PERSISTENTCONN	0x0020
#define FMT_NOSORT		0x0040
#define FMT_EXACT		0x0080
#define FMT_TUN_INFO		0x0100

#define SERVICE_NONE		0x0000
#define SERVICE_ADDR		0x0001
#define SERVICE_PORT		0x0002

/* default scheduler */
#define DEF_SCHED		"wlc"

/* default tunnel type */
#define DEF_TUNNEL_TYPE	"ipip"

/* default multicast interface name */
#define DEF_MCAST_IFN		"eth0"

#define CONN_PROC_FILE		"/proc/net/ip_vs_conn"

struct ipvs_command_entry {
	int			cmd;
	ipvs_service_t		svc;
	ipvs_dest_t		dest;
	ipvs_timeout_t		timeout;
	ipvs_daemon_t		daemon;
};

/* Use values outside ASCII range so that if an option has
 * a short name it can be used as the tag
 */
enum {
	TAG_SET	= 128,
	TAG_START_DAEMON,
	TAG_STOP_DAEMON	,
	TAG_MCAST_INTERFACE,
	TAG_TIMEOUT,
	TAG_DAEMON,
	TAG_STATS,
	TAG_RATE,
	TAG_THRESHOLDS,
	TAG_PERSISTENTCONN,
	TAG_SORT,
	TAG_NO_SORT,
	TAG_PERSISTENCE_ENGINE,
	TAG_SCTP_SERVICE,
	TAG_MCAST_GROUP,
	TAG_MCAST_PORT,
	TAG_MCAST_TTL,
	TAG_SYNC_MAXLEN,
	TAG_TUN_INFO,
	TAG_TUN_TYPE,
	TAG_TUN_PORT,
	TAG_TUN_NOCSUM,
	TAG_TUN_CSUM,
	TAG_TUN_REMCSUM,
};

/* various parsing helpers & parsing functions */
static int str_is_digit(const char *str);
static int string_to_number(const char *s, int min, int max);
static int host_to_addr(const char *name, struct in_addr *addr);
static char * addr_to_host(int af, const void *addr);
static char * addr_to_anyname(int af, const void *addr);
static int service_to_port(const char *name, unsigned short proto);
static char * port_to_service(unsigned short port, unsigned short proto);
static char * port_to_anyname(unsigned short port, unsigned short proto);
static char * addrport_to_anyname(int af, const void *addr, unsigned short port,
				  unsigned short proto, unsigned int format);
static int parse_service(char *buf, ipvs_service_t *svc);
static int parse_netmask(char *buf, u_int32_t *addr);
static int parse_timeout(char *buf, int min, int max);
static unsigned int parse_fwmark(char *buf);
static unsigned int parse_sched_flags(const char *sched, char *optarg);
static int parse_tun_type(const char *name);

/* check the options based on the commands_v_options table */
static void generic_opt_check(int command, unsigned long long options);
static void set_command(int *cmd, const int newcmd);
static void set_option(unsigned long long *options, int optc);

/* check the options based on the tunnel_types_v_options table */
static void tunnel_opt_check(int tun_type, unsigned long long options);

static void tryhelp_exit(const char *program, const int exit_status);
static void usage_exit(const char *program, const int exit_status);
static void version_exit(int exit_status);
static void version(FILE *stream);
static void fail(int err, char *msg, ...);

/* various listing functions */
static void list_conn(unsigned int format);
static void list_service(ipvs_service_t *svc, unsigned int format);
static void list_all(unsigned int format);
static void list_timeout(void);
static void list_daemon(void);

static int modprobe_ipvs(void);
static void check_ipvs_version(void);
static int process_options(int argc, char **argv, int reading_stdin);


int main(int argc, char **argv)
{
	int result;

	if (ipvs_init()) {
		/* try to insmod the ip_vs module if ipvs_init failed */
		if (modprobe_ipvs() || ipvs_init())
			fail(2, "Can't initialize ipvs: %s\n"
				"Are you sure that IP Virtual Server is "
				"built in the kernel or as module?",
			     ipvs_strerror(errno));
	}

	/* warn the user if the IPVS version is out of date */
	check_ipvs_version();

	/* list the table if there is no other arguement */
	if (argc == 1){
		list_all(FMT_NONE);
		ipvs_close();
		return 0;
	}

	/* process command line arguments */
	result = process_options(argc, argv, 0);

	ipvs_close();
	return result;
}

static int option_to_protocol(int opt)
{
	switch (opt) {
	case 't':
		return IPPROTO_TCP;
	case 'u':
		return IPPROTO_UDP;
	case TAG_SCTP_SERVICE:
		return IPPROTO_SCTP;
	default:
		return IPPROTO_IP;
	}
}

static char *option_from_protocol(int proto)
{
	switch (proto) {
	case IPPROTO_TCP:
		return "-t";
	case IPPROTO_UDP:
		return "-u";
	case IPPROTO_SCTP:
		return "--sctp-service";
	default:
		return NULL;
	}
}

static char *protocol_name(int proto)
{
	switch (proto) {
	case IPPROTO_TCP:
		return "TCP";
	case IPPROTO_UDP:
		return "UDP";
	case IPPROTO_SCTP:
		return "SCTP";
	default:
		return "?";
	}
}

static int
parse_options(int argc, char **argv, struct ipvs_command_entry *ce,
	      unsigned long long *options, unsigned int *format)
{
	int c, parse;
	poptContext context;
	char *optarg = NULL, sched_flags_arg[128];
	struct poptOption options_table[] = {
		{ "add-service", 'A', POPT_ARG_NONE, NULL, 'A', NULL, NULL },
		{ "edit-service", 'E', POPT_ARG_NONE, NULL, 'E', NULL, NULL },
		{ "delete-service", 'D', POPT_ARG_NONE, NULL, 'D', NULL, NULL },
		{ "clear", 'C', POPT_ARG_NONE, NULL, 'C', NULL, NULL },
		{ "list", 'L', POPT_ARG_NONE, NULL, 'L', NULL, NULL },
		{ "list", 'l', POPT_ARG_NONE, NULL, 'l', NULL, NULL },
		{ "zero", 'Z', POPT_ARG_NONE, NULL, 'Z', NULL, NULL },
		{ "add-server", 'a', POPT_ARG_NONE, NULL, 'a', NULL, NULL },
		{ "edit-server", 'e', POPT_ARG_NONE, NULL, 'e', NULL, NULL },
		{ "delete-server", 'd', POPT_ARG_NONE, NULL, 'd', NULL, NULL },
		{ "set", '\0', POPT_ARG_NONE, NULL, TAG_SET, NULL, NULL },
		{ "help", 'h', POPT_ARG_NONE, NULL, 'h', NULL, NULL },
		{ "version", 'v', POPT_ARG_NONE, NULL, 'v', NULL, NULL },
		{ "restore", 'R', POPT_ARG_NONE, NULL, 'R', NULL, NULL },
		{ "save", 'S', POPT_ARG_NONE, NULL, 'S', NULL, NULL },
		{ "start-daemon", '\0', POPT_ARG_STRING, &optarg,
		  TAG_START_DAEMON, NULL, NULL },
		{ "stop-daemon", '\0', POPT_ARG_STRING, &optarg,
		  TAG_STOP_DAEMON, NULL, NULL },
		{ "tcp-service", 't', POPT_ARG_STRING, &optarg, 't',
		  NULL, NULL },
		{ "udp-service", 'u', POPT_ARG_STRING, &optarg, 'u',
		  NULL, NULL },
		{ "sctp-service", '\0', POPT_ARG_STRING, &optarg,
		  TAG_SCTP_SERVICE, NULL, NULL },
		{ "fwmark-service", 'f', POPT_ARG_STRING, &optarg, 'f',
		  NULL, NULL },
		{ "scheduler", 's', POPT_ARG_STRING, &optarg, 's', NULL, NULL },
		{ "persistent", 'p', POPT_ARG_STRING|POPT_ARGFLAG_OPTIONAL,
		 &optarg, 'p', NULL, NULL },
		{ "netmask", 'M', POPT_ARG_STRING, &optarg, 'M', NULL, NULL },
		{ "real-server", 'r', POPT_ARG_STRING, &optarg, 'r',
		  NULL, NULL },
		{ "masquerading", 'm', POPT_ARG_NONE, NULL, 'm', NULL, NULL },
		{ "ipip", 'i', POPT_ARG_NONE, NULL, 'i', NULL, NULL },
		{ "gatewaying", 'g', POPT_ARG_NONE, NULL, 'g', NULL, NULL },
		{ "weight", 'w', POPT_ARG_STRING, &optarg, 'w', NULL, NULL },
		{ "u-threshold", 'x', POPT_ARG_STRING, &optarg, 'x',
		  NULL, NULL },
		{ "l-threshold", 'y', POPT_ARG_STRING, &optarg, 'y',
		  NULL, NULL },
		{ "numeric", 'n', POPT_ARG_NONE, NULL, 'n', NULL, NULL },
		{ "connection", 'c', POPT_ARG_NONE, NULL, 'c', NULL, NULL },
		{ "mcast-interface", '\0', POPT_ARG_STRING, &optarg,
		  TAG_MCAST_INTERFACE, NULL, NULL },
		{ "syncid", '\0', POPT_ARG_STRING, &optarg, 'I', NULL, NULL },
		{ "timeout", '\0', POPT_ARG_NONE, NULL, TAG_TIMEOUT,
		  NULL, NULL },
		{ "daemon", '\0', POPT_ARG_NONE, NULL, TAG_DAEMON, NULL, NULL },
		{ "stats", '\0', POPT_ARG_NONE, NULL, TAG_STATS, NULL, NULL },
		{ "rate", '\0', POPT_ARG_NONE, NULL, TAG_RATE, NULL, NULL },
		{ "thresholds", '\0', POPT_ARG_NONE, NULL,
		   TAG_THRESHOLDS, NULL, NULL },
		{ "persistent-conn", '\0', POPT_ARG_NONE, NULL,
		  TAG_PERSISTENTCONN, NULL, NULL },
		{ "nosort", '\0', POPT_ARG_NONE, NULL,
		   TAG_NO_SORT, NULL, NULL },
		{ "sort", '\0', POPT_ARG_NONE, NULL, TAG_SORT, NULL, NULL },
		{ "exact", 'X', POPT_ARG_NONE, NULL, 'X', NULL, NULL },
		{ "ipv6", '6', POPT_ARG_NONE, NULL, '6', NULL, NULL },
		{ "ops", 'o', POPT_ARG_NONE, NULL, 'o', NULL, NULL },
		{ "pe", '\0', POPT_ARG_STRING, &optarg, TAG_PERSISTENCE_ENGINE,
		  NULL, NULL },
		{ "sched-flags", 'b', POPT_ARG_STRING, &optarg, 'b',
		  NULL, NULL },
		{ "mcast-group", '\0', POPT_ARG_STRING, &optarg,
		  TAG_MCAST_GROUP, NULL, NULL },
		{ "mcast-port", '\0', POPT_ARG_STRING, &optarg,
		  TAG_MCAST_PORT, NULL, NULL },
		{ "mcast-ttl", '\0', POPT_ARG_STRING, &optarg,
		  TAG_MCAST_TTL, NULL, NULL },
		{ "sync-maxlen", '\0', POPT_ARG_STRING, &optarg,
		  TAG_SYNC_MAXLEN, NULL, NULL },
		{ "tun-info", '\0', POPT_ARG_NONE, NULL, TAG_TUN_INFO,
		  NULL, NULL },
		{ "tun-type", '\0', POPT_ARG_STRING, &optarg, TAG_TUN_TYPE,
		  NULL, NULL },
		{ "tun-port", '\0', POPT_ARG_STRING, &optarg, TAG_TUN_PORT,
		  NULL, NULL },
		{ "tun-nocsum", '\0', POPT_ARG_NONE, NULL, TAG_TUN_NOCSUM,
		  NULL, NULL },
		{ "tun-csum", '\0', POPT_ARG_NONE, NULL, TAG_TUN_CSUM,
		  NULL, NULL },
		{ "tun-remcsum", '\0', POPT_ARG_NONE, NULL, TAG_TUN_REMCSUM,
		  NULL, NULL },
		{ NULL, 0, 0, NULL, 0, NULL, NULL }
	};

	sched_flags_arg[0] = '\0';

	context = poptGetContext("ipvsadm", argc, (const char **)argv,
				 options_table, 0);

	if ((c = poptGetNextOpt(context)) < 0)
		tryhelp_exit(argv[0], -1);

	switch (c) {
	case 'A':
		set_command(&ce->cmd, CMD_ADD);
		break;
	case 'E':
		set_command(&ce->cmd, CMD_EDIT);
		break;
	case 'D':
		set_command(&ce->cmd, CMD_DEL);
		break;
	case 'a':
		set_command(&ce->cmd, CMD_ADDDEST);
		break;
	case 'e':
		set_command(&ce->cmd, CMD_EDITDEST);
		break;
	case 'd':
		set_command(&ce->cmd, CMD_DELDEST);
		break;
	case 'C':
		set_command(&ce->cmd, CMD_FLUSH);
		break;
	case 'L':
	case 'l':
		set_command(&ce->cmd, CMD_LIST);
		break;
	case 'Z':
		set_command(&ce->cmd, CMD_ZERO);
		break;
	case TAG_SET:
		set_command(&ce->cmd, CMD_TIMEOUT);
		break;
	case 'R':
		set_command(&ce->cmd, CMD_RESTORE);
		break;
	case 'S':
		set_command(&ce->cmd, CMD_SAVE);
		break;
	case TAG_START_DAEMON:
		set_command(&ce->cmd, CMD_STARTDAEMON);
		if (!strcmp(optarg, "master"))
			ce->daemon.state = IP_VS_STATE_MASTER;
		else if (!strcmp(optarg, "backup"))
			ce->daemon.state = IP_VS_STATE_BACKUP;
		else fail(2, "illegal start-daemon parameter specified");
		break;
	case TAG_STOP_DAEMON:
		set_command(&ce->cmd, CMD_STOPDAEMON);
		if (!strcmp(optarg, "master"))
			ce->daemon.state = IP_VS_STATE_MASTER;
		else if (!strcmp(optarg, "backup"))
			ce->daemon.state = IP_VS_STATE_BACKUP;
		else fail(2, "illegal start_daemon specified");
		break;
	case 'h':
		usage_exit(argv[0], 0);
		break;
	case 'v':
		version_exit(0);
		break;
	default:
		tryhelp_exit(argv[0], -1);
	}

	while ((c=poptGetNextOpt(context)) >= 0){
		switch (c) {
		case 't':
		case 'u':
		case TAG_SCTP_SERVICE:
			set_option(options, OPTC_SERVICE);
			ce->svc.protocol = option_to_protocol(c);
			parse = parse_service(optarg, &ce->svc);
			if (!(parse & SERVICE_ADDR))
				fail(2, "illegal virtual server "
				     "address[:port] specified");
			break;
		case 'f':
			set_option(options, OPTC_SERVICE);
			/*
			 * Set protocol to a sane values, even
			 * though it is not used
			 */
			ce->svc.af = AF_INET;
			ce->svc.protocol = IPPROTO_TCP;
			ce->svc.fwmark = parse_fwmark(optarg);
			break;
		case 's':
			set_option(options, OPTC_SCHEDULER);
			strncpy(ce->svc.sched_name,
				optarg, IP_VS_SCHEDNAME_MAXLEN - 1);
			break;
		case 'p':
			set_option(options, OPTC_PERSISTENT);
			ce->svc.flags |= IP_VS_SVC_F_PERSISTENT;
			ce->svc.timeout =
				parse_timeout(optarg, 1, MAX_TIMEOUT);
			break;
		case 'M':
			set_option(options, OPTC_NETMASK);
			if (ce->svc.af != AF_INET6) {
				parse = parse_netmask(optarg, &ce->svc.netmask);
				if (parse != 1)
					fail(2, "illegal virtual server "
					     "persistent mask specified");
			} else {
				ce->svc.netmask = atoi(optarg);
				if ((ce->svc.netmask < 1) || (ce->svc.netmask > 128))
					fail(2, "illegal ipv6 netmask specified");
			}
			break;
		case 'r':
			set_option(options, OPTC_SERVER);
			ipvs_service_t t_dest = ce->svc;
			parse = parse_service(optarg, &t_dest);
			ce->dest.af = t_dest.af;
			ce->dest.addr = t_dest.addr;
			ce->dest.port = t_dest.port;
			if (!(parse & SERVICE_ADDR))
				fail(2, "illegal real server "
				     "address[:port] specified");
			/* copy vport to dport if not specified */
			if (parse == 1)
				ce->dest.port = ce->svc.port;
			break;
		case 'i':
			set_option(options, OPTC_FORWARD);
			ce->dest.conn_flags = IP_VS_CONN_F_TUNNEL;
			break;
		case 'g':
			set_option(options, OPTC_FORWARD);
			ce->dest.conn_flags = IP_VS_CONN_F_DROUTE;
			break;
		case 'm':
			set_option(options, OPTC_FORWARD);
			ce->dest.conn_flags = IP_VS_CONN_F_MASQ;
			break;
		case 'w':
			set_option(options, OPTC_WEIGHT);
			if ((ce->dest.weight =
			     string_to_number(optarg, 0, INT_MAX)) == -1)
				fail(2, "illegal weight specified");
			break;
		case 'x':
			set_option(options, OPTC_UTHRESHOLD);
			if ((ce->dest.u_threshold =
			     string_to_number(optarg, 0, INT_MAX)) == -1)
				fail(2, "illegal u_threshold specified");
			break;
		case 'y':
			set_option(options, OPTC_LTHRESHOLD);
			if ((ce->dest.l_threshold =
			     string_to_number(optarg, 0, INT_MAX)) == -1)
				fail(2, "illegal l_threshold specified");
			break;
		case 'c':
			set_option(options, OPTC_CONNECTION);
			break;
		case 'n':
			set_option(options, OPTC_NUMERIC);
			*format |= FMT_NUMERIC;
			break;
		case TAG_MCAST_INTERFACE:
			set_option(options, OPTC_MCAST);
			strncpy(ce->daemon.mcast_ifn,
				optarg, IP_VS_IFNAME_MAXLEN - 1);
			break;
		case 'I':
			set_option(options, OPTC_SYNCID);
			if ((ce->daemon.syncid =
			     string_to_number(optarg, 0, 255)) == -1)
				fail(2, "illegal syncid specified");
			break;
		case TAG_TIMEOUT:
			set_option(options, OPTC_TIMEOUT);
			break;
		case TAG_DAEMON:
			set_option(options, OPTC_DAEMON);
			break;
		case TAG_STATS:
			set_option(options, OPTC_STATS);
			*format |= FMT_STATS;
			break;
		case TAG_RATE:
			set_option(options, OPTC_RATE);
			*format |= FMT_RATE;
			break;
		case TAG_THRESHOLDS:
			set_option(options, OPTC_THRESHOLDS);
			*format |= FMT_THRESHOLDS;
			break;
		case TAG_PERSISTENTCONN:
			set_option(options, OPTC_PERSISTENTCONN);
			*format |= FMT_PERSISTENTCONN;
			break;
		case TAG_NO_SORT:
			set_option(options, OPTC_NOSORT);
			*format |= FMT_NOSORT;
			break;
		case TAG_SORT:
			/* Sort is the default, this is a no-op for compatibility */
			break;
		case 'X':
			set_option(options, OPTC_EXACT);
			*format |= FMT_EXACT;
			break;
		case '6':
			if (ce->svc.fwmark) {
				ce->svc.af = AF_INET6;
				ce->svc.netmask = 128;
			} else {
				fail(2, "-6 used before -f\n");
			}
			break;
		case 'o':
			set_option(options, OPTC_ONEPACKET);
			ce->svc.flags |= IP_VS_SVC_F_ONEPACKET;
			break;
		case TAG_PERSISTENCE_ENGINE:
			set_option(options, OPTC_PERSISTENCE_ENGINE);
			strncpy(ce->svc.pe_name, optarg, IP_VS_PENAME_MAXLEN);
			break;
		case 'b':
			set_option(options, OPTC_SCHED_FLAGS);
			snprintf(sched_flags_arg, sizeof(sched_flags_arg),
				"%s", optarg);
			break;
		case TAG_MCAST_GROUP:
			set_option(options, OPTC_MCAST_GROUP);
			if (strchr(optarg, ':')) {
				if (inet_pton(AF_INET6, optarg,
					      &ce->daemon.mcast_group) <= 0 ||
				    !IN6_IS_ADDR_MULTICAST(
				     &ce->daemon.mcast_group.in6))
					fail(2, "invalid IPv6 mcast-group `%s'",
					     optarg);
				ce->daemon.mcast_af = AF_INET6;
			} else {
				if (inet_pton(AF_INET, optarg,
					      &ce->daemon.mcast_group) <= 0 ||
				    !IN_MULTICAST(ntohl(
						  ce->daemon.mcast_group.ip)))
					fail(2, "invalid IPv4 mcast-group `%s'",
					     optarg);
				ce->daemon.mcast_af = AF_INET;
			}
			break;
		case TAG_MCAST_PORT:
			set_option(options, OPTC_MCAST_PORT);
			parse = string_to_number(optarg, 1, 65535);
			if (parse == -1)
				fail(2, "illegal mcast-port specified");
			ce->daemon.mcast_port = parse;
			break;
		case TAG_MCAST_TTL:
			set_option(options, OPTC_MCAST_TTL);
			parse = string_to_number(optarg, 1, 255);
			if (parse == -1)
				fail(2, "illegal mcast-ttl specified");
			ce->daemon.mcast_ttl = parse;
			break;
		case TAG_SYNC_MAXLEN:
			set_option(options, OPTC_SYNC_MAXLEN);
			parse = string_to_number(optarg, 1, 65535 - 20 - 8);
			if (parse == -1)
				fail(2, "illegal sync-maxlen specified");
			ce->daemon.sync_maxlen = parse;
			break;
		case TAG_TUN_INFO:
			set_option(options, OPTC_TUN_INFO);
			*format |= FMT_TUN_INFO;
			break;
		case TAG_TUN_TYPE:
			set_option(options, OPTC_TUN_TYPE);
			parse = parse_tun_type(optarg);
			if (parse == -1)
				fail(2, "illegal tunnel type specified");
			ce->dest.tun_type = parse;
			break;
		case TAG_TUN_PORT:
			set_option(options, OPTC_TUN_PORT);
			parse = string_to_number(optarg, 1, 65535);
			if (parse == -1)
				fail(2, "illegal tunnel port specified");
			ce->dest.tun_port = htons(parse);
			break;
		case TAG_TUN_NOCSUM:
			set_option(options, OPTC_TUN_NOCSUM);
			ce->dest.tun_flags |= IP_VS_TUNNEL_ENCAP_FLAG_NOCSUM;
			break;
		case TAG_TUN_CSUM:
			set_option(options, OPTC_TUN_CSUM);
			ce->dest.tun_flags |= IP_VS_TUNNEL_ENCAP_FLAG_CSUM;
			break;
		case TAG_TUN_REMCSUM:
			set_option(options, OPTC_TUN_REMCSUM);
			ce->dest.tun_flags |= IP_VS_TUNNEL_ENCAP_FLAG_REMCSUM;
			break;
		default:
			fail(2, "invalid option `%s'",
			     poptBadOption(context, POPT_BADOPTION_NOALIAS));
		}
	}

	if (c < -1) {
		/* an error occurred during option processing */
		fprintf(stderr, "%s: %s\n",
			poptBadOption(context, POPT_BADOPTION_NOALIAS),
			poptStrerror(c));
		poptFreeContext(context);
		return -1;
	}

	if (ce->cmd == CMD_TIMEOUT) {
		char *optarg1, *optarg2;

		if ((optarg=(char *)poptGetArg(context))
		    && (optarg1=(char *)poptGetArg(context))
		    && (optarg2=(char *)poptGetArg(context))) {
			ce->timeout.tcp_timeout =
				parse_timeout(optarg, 0, MAX_TIMEOUT);
			ce->timeout.tcp_fin_timeout =
				parse_timeout(optarg1, 0, MAX_TIMEOUT);
			ce->timeout.udp_timeout =
				parse_timeout(optarg2, 0, MAX_TIMEOUT);
		} else
			fail(2, "--set option requires 3 timeout values");
	}

	if ((optarg=(char *)poptGetArg(context)))
		fail(2, "unexpected argument %s", optarg);

	if (sched_flags_arg[0]) {
		ce->svc.flags &= ~(IP_VS_SVC_F_SCHED1 |
				   IP_VS_SVC_F_SCHED2 |
				   IP_VS_SVC_F_SCHED3);
		ce->svc.flags |= parse_sched_flags(ce->svc.sched_name,
						   sched_flags_arg);
	}

	poptFreeContext(context);

	return 0;
}



static int restore_table(int argc, char **argv, int reading_stdin)
{
	int result = 0;
	dynamic_array_t *a;

	/* avoid infinite loop */
	if (reading_stdin != 0)
		tryhelp_exit(argv[0], -1);

	while ((a = config_stream_read(stdin, argv[0])) != NULL) {
		int i;
		if ((i = (int)dynamic_array_get_count(a)) > 1) {
			char **strv = dynamic_array_get_vector(a);
			result = process_options(i, strv, 1);
		}
		dynamic_array_destroy(a, DESTROY_STR);
	}
	return result;
}

static int process_options(int argc, char **argv, int reading_stdin)
{
	struct ipvs_command_entry ce;
	unsigned long long options = OPT_NONE;
	unsigned int format = FMT_NONE;
	unsigned int fwd_method;
	int result = 0;

	memset(&ce, 0, sizeof(struct ipvs_command_entry));
	ce.cmd = CMD_NONE;
	/* Set the default weight 1 */
	ce.dest.weight = 1;
	/* Set the default tunnel type 0(ipip) */
	ce.dest.tun_type = 0;
	/* Set the default tunnel port 0(n/a) */
	ce.dest.tun_port = 0;
	/* Set the default tunnel flags 0(nocsum) */
	ce.dest.tun_flags = 0;
	/* Set direct routing as default forwarding method */
	ce.dest.conn_flags = IP_VS_CONN_F_DROUTE;
	/* Set the default persistent granularity to /32 mask */
	ce.svc.netmask = ((u_int32_t) 0xffffffff);

	if (parse_options(argc, argv, &ce, &options, &format))
		return -1;

	generic_opt_check(ce.cmd, options);

	if (ce.cmd == CMD_ADD || ce.cmd == CMD_EDIT) {
		/* Make sure that port zero service is persistent */
		if (!ce.svc.fwmark && !ce.svc.port &&
		    !(ce.svc.flags & IP_VS_SVC_F_PERSISTENT))
			fail(2, "Zero port specified "
			     "for non-persistent service");

		if (ce.svc.flags & IP_VS_SVC_F_ONEPACKET &&
		    !ce.svc.fwmark && ce.svc.protocol != IPPROTO_UDP)
			fail(2, "One-Packet Scheduling is only "
			     "for UDP virtual services");

		/* Set the default scheduling algorithm if not specified */
		if (strlen(ce.svc.sched_name) == 0)
			strcpy(ce.svc.sched_name, DEF_SCHED);
	}

	if (ce.cmd == CMD_STARTDAEMON && strlen(ce.daemon.mcast_ifn) == 0)
		strcpy(ce.daemon.mcast_ifn, DEF_MCAST_IFN);

	fwd_method = ce.dest.conn_flags & IP_VS_CONN_F_FWD_MASK;

	if (ce.cmd == CMD_ADDDEST || ce.cmd == CMD_EDITDEST) {
		/*
		 * The destination port must be equal to the service port
		 * if the IP_VS_CONN_F_TUNNEL or IP_VS_CONN_F_DROUTE is set.
		 * Don't worry about this if fwmark is used.
		 */
		if (!ce.svc.fwmark &&
		    (fwd_method == IP_VS_CONN_F_TUNNEL ||
		     fwd_method == IP_VS_CONN_F_DROUTE))
			ce.dest.port = ce.svc.port;

		/* Tunneling allows different address family */
		if (ce.dest.af != ce.svc.af &&
		    fwd_method != IP_VS_CONN_F_TUNNEL)
			fail(2, "Different address family is allowed only "
			     "for tunneling servers");

		/* Only tunneling allows tunnel options */
		if (((options & (OPT_TUN_TYPE | OPT_TUN_PORT)) ||
		     (options & (OPT_TUN_NOCSUM | OPT_TUN_CSUM)) ||
		     (options & OPT_TUN_REMCSUM)) &&
		    fwd_method != IP_VS_CONN_F_TUNNEL)
			fail(2,
			     "Tunnel options conflict with forward method");

		tunnel_opt_check(ce.dest.tun_type, options);
	}

	switch (ce.cmd) {
	case CMD_LIST:
		if ((options & (OPT_CONNECTION|OPT_TIMEOUT|OPT_DAEMON) &&
		     options & (OPT_STATS|OPT_RATE|OPT_THRESHOLDS)) ||
		    (options & (OPT_TIMEOUT|OPT_DAEMON) &&
		     options & OPT_PERSISTENTCONN))
			fail(2, "options conflicts in the list command");

		if (options & OPT_CONNECTION)
			list_conn(format);
		else if (options & OPT_SERVICE)
			list_service(&ce.svc, format);
		else if (options & OPT_TIMEOUT)
			list_timeout();
		else if (options & OPT_DAEMON)
			list_daemon();
		else
			list_all(format);
		return 0;

	case CMD_RESTORE:
		return restore_table(argc, argv, reading_stdin);

	case CMD_SAVE:
		format |= FMT_RULE;
		list_all(format);
		return 0;

	case CMD_FLUSH:
		result = ipvs_flush();
		break;

	case CMD_ADD:
		result = ipvs_add_service(&ce.svc);
		break;

	case CMD_EDIT:
		result = ipvs_update_service(&ce.svc);
		break;

	case CMD_DEL:
		result = ipvs_del_service(&ce.svc);
		break;

	case CMD_ZERO:
		result = ipvs_zero_service(&ce.svc);
		break;

	case CMD_ADDDEST:
		result = ipvs_add_dest(&ce.svc, &ce.dest);
		break;

	case CMD_EDITDEST:
		result = ipvs_update_dest(&ce.svc, &ce.dest);
		break;

	case CMD_DELDEST:
		result = ipvs_del_dest(&ce.svc, &ce.dest);
		break;

	case CMD_TIMEOUT:
		result = ipvs_set_timeout(&ce.timeout);
		break;

	case CMD_STARTDAEMON:
		result = ipvs_start_daemon(&ce.daemon);
		break;

	case CMD_STOPDAEMON:
		result = ipvs_stop_daemon(&ce.daemon);
	}

	if (result)
		fprintf(stderr, "%s\n", ipvs_strerror(errno));

	return result;
}


static int string_to_number(const char *s, int min, int max)
{
	long number;
	char *end;

	errno = 0;
	number = strtol(s, &end, 10);
	if (*end == '\0' && end != s) {
		/* We parsed a number, let's see if we want this. */
		if (errno != ERANGE && min <= number && number <= max)
			return number;
	}
	return -1;
}


/*
 * Parse the timeout value.
 */
static int parse_timeout(char *buf, int min, int max)
{
	int i;

	/* it is just for parsing timeout of persistent service */
	if (buf == NULL)
		return IPVS_SVC_PERSISTENT_TIMEOUT;

	if ((i=string_to_number(buf, min, max)) == -1)
		fail(2, "invalid timeout value `%s' specified", buf);

	return i;
}


/*
 * Parse IP fwmark from the argument.
 */
static unsigned int parse_fwmark(char *buf)
{
	unsigned long l;
	char *end;

	errno = 0;
	l = strtol(buf, &end, 10);
	if (*end != '\0' || end == buf ||
	    errno == ERANGE || l <= 0 || l > UINT_MAX)
		fail(2, "invalid fwmark value `%s' specified", buf);

	return l;
}


/*
 * Get netmask.
 * Return 0 if failed,
 *	  1 if addr read
 */
static int parse_netmask(char *buf, u_int32_t *addr)
{
	struct in_addr inaddr;

	if(buf == NULL)
		return 0;

	if (inet_aton(buf, &inaddr) != 0)
		*addr = inaddr.s_addr;
	else if (host_to_addr(buf, &inaddr) != -1)
		*addr = inaddr.s_addr;
	else
		return 0;

	return 1;
}


/*
 * Get IP address and port from the argument.
 * Result is a logical or of
 * SERVICE_NONE:   no service elements set/error
 * SERVICE_ADDR:   addr set
 * SERVICE_PORT:   port set
 */
static int
parse_service(char *buf, ipvs_service_t *svc)
{
	char *portp = NULL;
	long portn;
	int result=SERVICE_NONE;
	struct in_addr inaddr;
	struct in6_addr inaddr6;

	if (buf == NULL || str_is_digit(buf))
		return SERVICE_NONE;
	if (buf[0] == '[') {
		buf++;
		portp = strchr(buf, ']');
		if (portp == NULL)
			return SERVICE_NONE;
		*portp = '\0';
		portp++;
		if (*portp == ':')
			*portp = '\0';
		else
			return SERVICE_NONE;
	}
	if (inet_pton(AF_INET6, buf, &inaddr6) > 0) {
		svc->addr.in6 = inaddr6;
		svc->af = AF_INET6;
		svc->netmask = 128;
	} else {
		portp = strrchr(buf, ':');
		if (portp != NULL)
			*portp = '\0';

		if (inet_aton(buf, &inaddr) != 0) {
			svc->addr.ip = inaddr.s_addr;
			svc->af = AF_INET;
		} else if (host_to_addr(buf, &inaddr) != -1) {
			svc->addr.ip = inaddr.s_addr;
			svc->af = AF_INET;
		} else
			return SERVICE_NONE;
	}

	result |= SERVICE_ADDR;

	if (portp != NULL) {
		result |= SERVICE_PORT;

		if ((portn = string_to_number(portp+1, 0, 65535)) != -1)
			svc->port = htons(portn);
		else if ((portn = service_to_port(portp+1, svc->protocol)) != -1)
			svc->port = htons(portn);
		else
			return SERVICE_NONE;
	}

	return result;
}

static unsigned int parse_sched_flags(const char *sched, char *optarg)
{
	unsigned int flags = 0;
	char *flag;

	sched = (sched && *sched) ? sched : DEF_SCHED;

	flag = strtok(optarg, ",");
	do {
		if (!strcmp(flag, "flag-1")) {
			flags |= IP_VS_SVC_F_SCHED1;
		} else if (!strcmp(flag, "flag-2")) {
			flags |= IP_VS_SVC_F_SCHED2;
		} else if (!strcmp(flag, "flag-3")) {
			flags |= IP_VS_SVC_F_SCHED3;
		} else if (!strcmp(flag, "sh-fallback")) {
			flags |= IP_VS_SVC_F_SCHED_SH_FALLBACK;
			if (strcmp(sched, "sh"))
				fail(2, "incompatible scheduler flag `%s'",
				     flag);
		} else if (!strcmp(flag, "sh-port")) {
			flags |= IP_VS_SVC_F_SCHED_SH_PORT;
			if (strcmp(sched, "sh"))
				fail(2, "incompatible scheduler flag `%s'",
				     flag);
		} else if (!strcmp(flag, "mh-fallback")) {
			flags |= IP_VS_SVC_F_SCHED_MH_FALLBACK;
			if (strcmp(sched, "mh"))
				fail(2, "incompatible scheduler flag `%s'",
				     flag);
		} else if (!strcmp(flag, "mh-port")) {
			flags |= IP_VS_SVC_F_SCHED_MH_PORT;
			if (strcmp(sched, "mh"))
				fail(2, "incompatible scheduler flag `%s'",
				     flag);
		} else {
			fail(2, "invalid scheduler flag `%s'", flag);
		}
	} while ((flag = strtok(NULL, ",")) != NULL);

	return flags;
}

static int parse_tun_type(const char *tun_type)
{
	int type = -1;

	if (!strcmp(tun_type, "ipip"))
		type = IP_VS_CONN_F_TUNNEL_TYPE_IPIP;
	else if (!strcmp(tun_type, "gue"))
		type = IP_VS_CONN_F_TUNNEL_TYPE_GUE;
	else if (!strcmp(tun_type, "gre"))
		type = IP_VS_CONN_F_TUNNEL_TYPE_GRE;
	else
		type = -1;

	return type;
}

static void
generic_opt_check(int command, unsigned long long options)
{
	int i, j;
	int last = 0, count = 0;

	/* Check that commands are valid with options. */
	i = command - CMD_NONE -1;

	for (j = 0; j < NUMBER_OF_OPT; j++) {
		if (!(options & (1ULL << j))) {
			if (commands_v_options[i][j] == '+')
				fail(2, "You need to supply the '%s' "
				     "option for the '%s' command",
				     optnames[j], cmdnames[i]);
		} else {
			if (commands_v_options[i][j] == 'x')
				fail(2, "Illegal '%s' option with "
				     "the '%s' command",
				     optnames[j], cmdnames[i]);
			if (commands_v_options[i][j] == '1') {
				count++;
				if (count == 1) {
					last = j;
					continue;
				}
				fail(2, "The option '%s' conflicts with the "
				     "'%s' option in the '%s' command",
				     optnames[j], optnames[last], cmdnames[i]);
			}
		}
	}
}

static void
tunnel_opt_check(int tun_type, unsigned long long options)
{
	int i, j, k;
	int last = 0, count = 0;

	/* Check that tunnel types are valid with options. */
	i = tun_type;

	for (j = 0; j < NUMBER_OF_TUN_OPT; j++) {
		k = tunopts[j];
		if (!(options & (1ULL << k))) {
			if (tunnel_types_v_options[i][j] == '+')
				fail(2, "You need to supply the '%s' "
				     "option for the '%s' tunnel type",
				     optnames[k], tunnames[i]);
		} else {
			if (tunnel_types_v_options[i][j] == 'x')
				fail(2, "Illegal '%s' option with "
				     "the '%s' tunnel type",
				     optnames[k], tunnames[i]);
			if (tunnel_types_v_options[i][j] == '1') {
				count++;
				if (count == 1) {
					last = k;
					continue;
				}
				fail(2, "The option '%s' conflicts with the "
				     "'%s' option in the '%s' tunnel type",
				     optnames[k], optnames[last], tunnames[i]);
			}
		}
	}
}

static void
set_command(int *cmd, const int newcmd)
{
	if (*cmd != CMD_NONE)
		fail(2, "multiple commands specified");
	*cmd = newcmd;
}

static void
set_option(unsigned long long *options, int optc)
{
	unsigned long long option = 1ULL << optc;
	if (*options & option)
		fail(2, "multiple '%s' options specified", optnames[optc]);
	*options |= option;
}


static void tryhelp_exit(const char *program, const int exit_status)
{
	fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
		program, program);
	exit(exit_status);
}


static void usage_exit(const char *program, const int exit_status)
{
	FILE *stream;

	if (exit_status != 0)
		stream = stderr;
	else
		stream = stdout;

	version(stream);
	fprintf(stream,
		"Usage:\n"
		"  %s -A|E virtual-service [-s scheduler] [-p [timeout]] [-M netmask] [--pe persistence_engine] [-b sched-flags]\n"
		"  %s -D virtual-service\n"
		"  %s -C\n"
		"  %s -R\n"
		"  %s -S [-n]\n"
		"  %s -a|e virtual-service -r server-address [options]\n"
		"  %s -d virtual-service -r server-address\n"
		"  %s -L|l [virtual-service] [options]\n"
		"  %s -Z [virtual-service]\n"
		"  %s --set tcp tcpfin udp\n"
		"  %s --start-daemon {master|backup} [daemon-options]\n"
		"  %s --stop-daemon {master|backup}\n"
		"  %s -h\n\n",
		program, program, program,
		program, program, program, program, program,
		program, program, program, program, program);

	fprintf(stream,
		"Commands:\n"
		"Either long or short options are allowed.\n"
		"  --add-service     -A        add virtual service with options\n"
		"  --edit-service    -E        edit virtual service with options\n"
		"  --delete-service  -D        delete virtual service\n"
		"  --clear           -C        clear the whole table\n"
		"  --restore         -R        restore rules from stdin\n"
		"  --save            -S        save rules to stdout\n"
		"  --add-server      -a        add real server with options\n"
		"  --edit-server     -e        edit real server with options\n"
		"  --delete-server   -d        delete real server\n"
		"  --list            -L|-l     list the table\n"
		"  --zero            -Z        zero counters in a service or all services\n"
		"  --set tcp tcpfin udp        set connection timeout values\n"
		"  --start-daemon              start connection sync daemon\n"
		"  --stop-daemon               stop connection sync daemon\n"
		"  --help            -h        display this help message\n\n"
		);

	fprintf(stream,
		"virtual-service:\n"
		"  --tcp-service|-t  service-address   service-address is host[:port]\n"
		"  --udp-service|-u  service-address   service-address is host[:port]\n"
		"  --sctp-service    service-address   service-address is host[:port]\n"
		"  --fwmark-service|-f fwmark          fwmark is an integer greater than zero\n"
		"\n");

	fprintf(stream,
		"Options:\n"
		"  --ipv6         -6                   fwmark entry uses IPv6\n"
		"  --scheduler    -s scheduler         one of " SCHEDULERS ",\n"
		"                                      the default scheduler is %s.\n"
		"  --pe            engine              alternate persistence engine may be " PE_LIST ",\n"
		"                                      not set by default.\n"
		"  --persistent   -p [timeout]         persistent service\n"
		"  --netmask      -M netmask           persistent granularity mask\n"
		"  --real-server  -r server-address    server-address is host (and port)\n"
		"  --gatewaying   -g                   gatewaying (direct routing) (default)\n"
		"  --ipip         -i                   ipip encapsulation (tunneling)\n"
		"  --masquerading -m                   masquerading (NAT)\n"
		"  --tun-type      type                one of ipip|gue|gre,\n"
		"                                      the default tunnel type is %s.\n"
		"  --tun-port      port                tunnel destination port\n"
		"  --tun-nocsum                        tunnel encapsulation without checksum\n"
		"  --tun-csum                          tunnel encapsulation with checksum\n"
		"  --tun-remcsum                       tunnel encapsulation with remote checksum\n"
		"  --weight       -w weight            capacity of real server\n"
		"  --u-threshold  -x uthreshold        upper threshold of connections\n"
		"  --l-threshold  -y lthreshold        lower threshold of connections\n"
		"  --connection   -c                   output of current IPVS connections\n"
		"  --timeout                           output of timeout (tcp tcpfin udp)\n"
		"  --daemon                            output of daemon information\n"
		"  --stats                             output of statistics information\n"
		"  --rate                              output of rate information\n"
		"  --exact                             expand numbers (display exact values)\n"
		"  --thresholds                        output of thresholds information\n"
		"  --persistent-conn                   output of persistent connection info\n"
		"  --tun-info                          output of tunnel information\n"
		"  --nosort                            disable sorting output of service/server entries\n"
		"  --sort                              does nothing, for backwards compatibility\n"
		"  --ops          -o                   one-packet scheduling\n"
		"  --numeric      -n                   numeric output of addresses and ports\n"
		"  --sched-flags  -b flags             scheduler flags (comma-separated)\n",
		DEF_SCHED, DEF_TUNNEL_TYPE);

	fprintf(stream,
		"Daemon Options:\n"
		"  --syncid sid                        syncid for connection sync (default=255)\n"
		"  --sync-maxlen length                Max sync message length (default=1472)\n"
		"  --mcast-interface interface         multicast interface for connection sync\n"
		"  --mcast-group address               IPv4/IPv6 group (default=224.0.0.81)\n"
		"  --mcast-port port                   UDP port (default=8848)\n"
		"  --mcast-ttl ttl                     Multicast TTL (default=1)\n"
		);

	exit(exit_status);
}


static void version_exit(const int exit_status)
{
	FILE *stream;

	if (exit_status != 0)
		stream = stderr;
	else
		stream = stdout;

	version(stream);

	exit(exit_status);
}


static void version(FILE *stream)
{
	fprintf(stream,
		"ipvsadm " IPVSADM_VERSION " (compiled with "
		IPVS_OPTION_PROCESSING " and IPVS v%d.%d.%d)\n",
		NVERSION(IP_VS_VERSION_CODE));
}


static void fail(int err, char *msg, ...)
{
	va_list args;

	va_start(args, msg);
	vfprintf(stderr, msg, args);
	va_end(args);
	fprintf(stderr, "\n");
	exit(err);
}


static int modprobe_ipvs(void)
{
	char *argv[] = { "/sbin/modprobe", "--", "ip_vs", NULL };
	int child;
	int status;
	int rc;

	if (!(child = fork())) {
		execv(argv[0], argv);
		exit(1);
	}

	rc = waitpid(child, &status, 0);

	if (rc == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) {
		return 1;
	}

	return 0;
}


static void check_ipvs_version(void)
{
	/* verify the IPVS version */
	if (ipvs_info.version <
	    IPVS_VERSION(MINIMUM_IPVS_VERSION_MAJOR,
			 MINIMUM_IPVS_VERSION_MINOR,
			 MINIMUM_IPVS_VERSION_PATCH)) {
		fprintf(stderr,
			"Warning: IPVS version mismatch: \n"
			"  Kernel compiled with IPVS version %d.%d.%d\n"
			"  ipvsadm " IPVSADM_VERSION_NO
			"  requires minimum IPVS version %d.%d.%d\n\n",
			NVERSION(ipvs_info.version),
			MINIMUM_IPVS_VERSION_MAJOR,
			MINIMUM_IPVS_VERSION_MINOR,
			MINIMUM_IPVS_VERSION_PATCH);
	}
}


static void print_conn(char *buf, unsigned int format)
{
	char            protocol[8];
	unsigned short  proto;
	union nf_inet_addr  caddr;
	unsigned short  cport;
	union nf_inet_addr  vaddr;
	unsigned short  vport;
	union nf_inet_addr  daddr;
	unsigned short  dport;
	char            state[16];
	unsigned int    expires;
	unsigned short  af = AF_INET;
	unsigned short  daf = AF_INET;
	char		pe_name[IP_VS_PENAME_MAXLEN + 1];
	char		pe_data[IP_VS_PEDATA_MAXLEN + 1];

	int n;
	char temp1[INET6_ADDRSTRLEN], temp2[INET6_ADDRSTRLEN], temp3[INET6_ADDRSTRLEN];
	char *cname, *vname, *dname;
	unsigned int	minutes, seconds;
	char		expire_str[12];

	if ((n = sscanf(buf, "%s %s %hX %s %hX %s %hX %s %d %s %s",
			protocol, temp1, &cport, temp2, &vport,
			temp3, &dport, state, &expires,
			pe_name, pe_data)) == -1)
		exit(1);

	if (strcmp(protocol, "TCP") == 0)
		proto = IPPROTO_TCP;
	else if (strcmp(protocol, "UDP") == 0)
		proto = IPPROTO_UDP;
	else if (strcmp(protocol, "SCTP") == 0)
		proto = IPPROTO_SCTP;
	else
		proto = 0;

	if (inet_pton(AF_INET6, temp1, &caddr.in6) > 0) {
		inet_pton(AF_INET6, temp2, &vaddr.in6);
		af = AF_INET6;
	} else if (inet_pton(AF_INET, temp1, &caddr.ip) > 0) {
		inet_pton(AF_INET, temp2, &vaddr.ip);
	} else {
		caddr.ip = (__u32) htonl(strtoul(temp1, NULL, 16));
		vaddr.ip = (__u32) htonl(strtoul(temp2, NULL, 16));
	}

	if (inet_pton(AF_INET6, temp3, &daddr.in6) > 0)
		daf = AF_INET6;
	else if (inet_pton(AF_INET, temp3, &daddr.ip) <= 0)
		daddr.ip = (__u32) htonl(strtoul(temp3, NULL, 16));

	if (!(cname = addrport_to_anyname(af, &caddr, cport, proto, format)))
		exit(1);
	if (!(vname = addrport_to_anyname(af, &vaddr, vport, proto, format)))
		exit(1);
	if (!(dname = addrport_to_anyname(daf, &daddr, dport, proto, format)))
		exit(1);

	seconds = expires % 60;
	minutes = expires / 60;
	sprintf(expire_str, "%02d:%02d", minutes, seconds);

	if (format & FMT_PERSISTENTCONN && n == 11)
		printf("%-3s %-6s %-11s %-18s %-18s %-16s %-18s %s\n",
		       protocol, expire_str, state, cname, vname, dname,
		       pe_name, pe_data);
	else
		printf("%-3s %-6s %-11s %-18s %-18s %s\n",
		       protocol, expire_str, state, cname, vname, dname);

	free(cname);
	free(vname);
	free(dname);
}


void list_conn(unsigned int format)
{
	static char buffer[256];
	FILE *handle;

	handle = fopen(CONN_PROC_FILE, "r");
	if (!handle) {
		fprintf(stderr, "cannot open file %s\n", CONN_PROC_FILE);
		exit(1);
	}

	/* read the first line */
	if (fgets(buffer, sizeof(buffer), handle) == NULL) {
		fprintf(stderr, "unexpected input from %s\n",
			CONN_PROC_FILE);
		exit(1);
	}
	printf("IPVS connection entries\n");
	if (format & FMT_PERSISTENTCONN)
		printf("pro expire %-11s %-18s %-18s %-18s %-16s %s\n",
		       "state", "source", "virtual", "destination",
		       "pe name", "pe_data");
	else
		printf("pro expire %-11s %-18s %-18s %s\n",
		       "state", "source", "virtual", "destination");

	/*
	 * Print the VS information according to the format
	 */
	while (!feof(handle)) {
		if (fgets(buffer, sizeof(buffer), handle))
			print_conn(buffer, format);
	}

	fclose(handle);
}


static inline char *fwd_name(unsigned flags)
{
	char *fwd = NULL;

	switch (flags & IP_VS_CONN_F_FWD_MASK) {
	case IP_VS_CONN_F_MASQ:
		fwd = "Masq";
		break;
	case IP_VS_CONN_F_LOCALNODE:
		fwd = "Local";
		break;
	case IP_VS_CONN_F_TUNNEL:
		fwd = "Tunnel";
		break;
	case IP_VS_CONN_F_DROUTE:
		fwd = "Route";
		break;
	}
	return fwd;
}

static inline char *fwd_switch(unsigned flags)
{
	char *swt = NULL;

	switch (flags & IP_VS_CONN_F_FWD_MASK) {
	case IP_VS_CONN_F_MASQ:
		swt = "-m"; break;
	case IP_VS_CONN_F_TUNNEL:
		swt = "-i"; break;
	case IP_VS_CONN_F_LOCALNODE:
	case IP_VS_CONN_F_DROUTE:
		swt = "-g"; break;
	}
	return swt;
}


static inline char *fwd_tun_info(ipvs_dest_entry_t *e)
{
	char *info = malloc(16);

	if (!info)
		return NULL;

	switch (e->conn_flags & IP_VS_CONN_F_FWD_MASK) {
	case IP_VS_CONN_F_TUNNEL:
		switch (e->tun_type) {
		case IP_VS_CONN_F_TUNNEL_TYPE_IPIP:
			snprintf(info, 16, "%s", tunnames[e->tun_type]);
			break;
		case IP_VS_CONN_F_TUNNEL_TYPE_GUE:
			snprintf(info, 16, "%s:%d:%s",
				 tunnames[e->tun_type], ntohs(e->tun_port),
				 tunflags[e->tun_flags]);
			break;
		case IP_VS_CONN_F_TUNNEL_TYPE_GRE:
			snprintf(info, 16, "%s:%s",
				 tunnames[e->tun_type],
				 tunflags[e->tun_flags]);
			break;
		default:
			free(info);
			return NULL;
		}
		break;
	default:
		free(info);
		return NULL;
	}
	return info;
}

static void print_largenum(unsigned long long i, unsigned int format)
{
	if (format & FMT_EXACT) {
		char mytmp[32];
		int len;

		len = snprintf(mytmp, 32, "%llu", i);
		printf("%*llu", len <= 8 ? 9 : len + 1, i);
		return;
	}

	if (i < 100000000)			/* less than 100 million */
		printf("%9llu", i);
	else if (i < 1000000000)		/* less than 1 billion */
		printf("%8lluK", i / 1000);
	else if (i < 100000000000ULL)		/* less than 100 billion */
		printf("%8lluM", i / 1000000);
	else if (i < 100000000000000ULL)	/* less than 100 trillion */
		printf("%8lluG", i / 1000000000ULL);
	else
		printf("%8lluT", i / 1000000000000ULL);
}

static void print_sched_flags(ipvs_service_entry_t *se)
{
	char flags[64];

	flags[0] = '\0';

	if (!strcmp(se->sched_name, "sh")) {
		if (se->flags & IP_VS_SVC_F_SCHED_SH_FALLBACK)
			strcat(flags, "sh-fallback,");
		if (se->flags & IP_VS_SVC_F_SCHED_SH_PORT)
			strcat(flags, "sh-port,");
	} else if (!strcmp(se->sched_name, "mh")) {
		if (se->flags & IP_VS_SVC_F_SCHED_MH_FALLBACK)
			strcat(flags, "mh-fallback,");
		if (se->flags & IP_VS_SVC_F_SCHED_MH_PORT)
			strcat(flags, "mh-port,");
	} else {
		if (se->flags & IP_VS_SVC_F_SCHED1)
			strcat(flags, "flag-1,");
		if (se->flags & IP_VS_SVC_F_SCHED2)
			strcat(flags, "flag-2,");
		if (se->flags & IP_VS_SVC_F_SCHED3)
			strcat(flags, "flag-3,");
	}

	if (flags[0]) {
		flags[strlen(flags)-1] = '\0';
		printf("%s", flags);
	}
}

static void print_title(unsigned int format)
{
	if (format & FMT_STATS)
		printf("%-33s %8s %8s %8s %8s %8s\n"
		       "  -> RemoteAddress:Port\n",
		       "Prot LocalAddress:Port",
		       "Conns", "InPkts", "OutPkts", "InBytes", "OutBytes");
	else if (format & FMT_RATE)
		printf("%-33s %8s %8s %8s %8s %8s\n"
		       "  -> RemoteAddress:Port\n",
		       "Prot LocalAddress:Port",
		       "CPS", "InPPS", "OutPPS", "InBPS", "OutBPS");
	else if (format & FMT_THRESHOLDS)
		printf("%-33s %-10s %-10s %-10s %-10s\n"
		       "  -> RemoteAddress:Port\n",
		       "Prot LocalAddress:Port",
		       "Uthreshold", "Lthreshold", "ActiveConn", "InActConn");
	else if (format & FMT_PERSISTENTCONN)
		printf("%-33s %-9s %-11s %-10s %-10s\n"
		       "  -> RemoteAddress:Port\n",
		       "Prot LocalAddress:Port",
		       "Weight", "PersistConn", "ActiveConn", "InActConn");
	else if ((format & FMT_TUN_INFO))
		printf("Prot LocalAddress:Port Scheduler Flags\n"
		       "  -> RemoteAddress:Port           Forward TunnelInfo    Weight ActiveConn InActConn\n");
	else if (!(format & FMT_RULE))
		printf("Prot LocalAddress:Port Scheduler Flags\n"
		       "  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn\n");
}


static inline void
print_tunnel_rule(char *svc_name, char *dname, ipvs_dest_entry_t *e)
{
	switch (e->tun_type) {
	case IP_VS_CONN_F_TUNNEL_TYPE_GRE:
		printf("-a %s -r %s %s -w %d --tun-type %s %s\n",
		       svc_name,
		       dname,
		       fwd_switch(e->conn_flags),
		       e->weight,
		       tunnames[e->tun_type],
		       tun_flags_opts[e->tun_flags]);
		break;
	case IP_VS_CONN_F_TUNNEL_TYPE_GUE:
		printf("-a %s -r %s %s -w %d --tun-type %s --tun-port %d %s\n",
		       svc_name,
		       dname,
		       fwd_switch(e->conn_flags),
		       e->weight,
		       tunnames[e->tun_type],
		       ntohs(e->tun_port),
		       tun_flags_opts[e->tun_flags]);
		break;
	case IP_VS_CONN_F_TUNNEL_TYPE_IPIP:
		printf("-a %s -r %s %s -w %d --tun-type %s\n",
		       svc_name,
		       dname,
		       fwd_switch(e->conn_flags),
		       e->weight,
		       tunnames[e->tun_type]);
		break;
	default:
		printf("-a %s -r %s %s -w %d\n",
		       svc_name,
		       dname,
		       fwd_switch(e->conn_flags),
		       e->weight);
		break;
	}
}

static void
print_service_entry(ipvs_service_entry_t *se, unsigned int format)
{
	struct ip_vs_get_dests *d;
	char svc_name[1024];
	int i;

	if (!(d = ipvs_get_dests(se))) {
		fprintf(stderr, "%s\n", ipvs_strerror(errno));
		exit(1);
	}

	if (se->fwmark) {
		if (format & FMT_RULE)
			if (se->af == AF_INET6)
				sprintf(svc_name, "-f %d -6", se->fwmark);
			else
				sprintf(svc_name, "-f %d", se->fwmark);
		else
			if (se->af == AF_INET6)
				sprintf(svc_name, "FWM  %d IPv6", se->fwmark);
			else
				sprintf(svc_name, "FWM  %d", se->fwmark);
	} else {
		char *vname;

		if (!(vname = addrport_to_anyname(se->af, &se->addr, ntohs(se->port),
						  se->protocol, format)))
			fail(2, "addrport_to_anyname: %s", strerror(errno));
		if (format & FMT_RULE) {
			char *stype = option_from_protocol(se->protocol) ? :
				      "--xxx-service";

			snprintf(svc_name, sizeof(svc_name), "%s %s",
				 stype, vname);
		} else {
			char *stype = protocol_name(se->protocol);

			snprintf(svc_name, sizeof(svc_name), "%-4s %s",
				 stype, vname);
			if (se->af != AF_INET6)
				svc_name[33] = '\0';
		}
		free(vname);
	}

	/* print virtual service info */
	if (format & FMT_RULE) {
		printf("-A %s -s %s", svc_name, se->sched_name);
		if (se->flags & IP_VS_SVC_F_PERSISTENT) {
			printf(" -p %u", se->timeout);
			if (se->af == AF_INET)
				if (se->netmask != (unsigned long int) 0xffffffff) {
					struct in_addr mask;
					mask.s_addr = se->netmask;
					printf(" -M %s", inet_ntoa(mask));
				}
			if (se->af == AF_INET6)
				if (se->netmask != 128) {
					printf(" -M %i", se->netmask);
				}
		}
		if (se->pe_name[0])
			printf(" --pe %s", se->pe_name);
		if (se->flags & IP_VS_SVC_F_ONEPACKET)
			printf(" -o");
		if (se->flags & (IP_VS_SVC_F_SCHED1 |
				 IP_VS_SVC_F_SCHED2 |
				 IP_VS_SVC_F_SCHED3)) {
			printf(" -b ");
			print_sched_flags(se);
		}
	} else if (format & FMT_STATS) {
		printf("%-33s", svc_name);
		print_largenum(se->stats64.conns, format);
		print_largenum(se->stats64.inpkts, format);
		print_largenum(se->stats64.outpkts, format);
		print_largenum(se->stats64.inbytes, format);
		print_largenum(se->stats64.outbytes, format);
	} else if (format & FMT_RATE) {
		printf("%-33s", svc_name);
		print_largenum(se->stats64.cps, format);
		print_largenum(se->stats64.inpps, format);
		print_largenum(se->stats64.outpps, format);
		print_largenum(se->stats64.inbps, format);
		print_largenum(se->stats64.outbps, format);
	} else {
		printf("%s %s", svc_name, se->sched_name);
		if (se->flags & (IP_VS_SVC_F_SCHED1 |
				 IP_VS_SVC_F_SCHED2 |
				 IP_VS_SVC_F_SCHED3)) {
			printf(" (");
			print_sched_flags(se);
			printf(")");
		}
		if (se->flags & IP_VS_SVC_F_PERSISTENT) {
			printf(" persistent %u", se->timeout);
			if (se->af == AF_INET)
				if (se->netmask != (unsigned long int) 0xffffffff) {
					struct in_addr mask;
					mask.s_addr = se->netmask;
					printf(" mask %s", inet_ntoa(mask));
				}
			if (se->af == AF_INET6)
				if (se->netmask != 128)
					printf(" mask %i", se->netmask);
			if (se->pe_name[0])
				printf(" pe %s", se->pe_name);
		}
		if (se->flags & IP_VS_SVC_F_ONEPACKET)
			printf(" ops");
	}
	printf("\n");

	/* print all the destination entries */
	if (!(format & FMT_NOSORT))
		ipvs_sort_dests(d, ipvs_cmp_dests);

	for (i = 0; i < d->num_dests; i++) {
		char *dname;
		ipvs_dest_entry_t *e = &d->entrytable[i];
		unsigned int fwd_method = e->conn_flags & IP_VS_CONN_F_FWD_MASK;

		if (!(dname = addrport_to_anyname(e->af, &(e->addr), ntohs(e->port),
						  se->protocol, format))) {
			fprintf(stderr, "addrport_to_anyname fails\n");
			exit(1);
		}
		if (!(format & FMT_RULE) && (e->af != AF_INET6))
			dname[28] = '\0';

		if (format & FMT_RULE) {
			if (fwd_method == IP_VS_CONN_F_TUNNEL) {
				print_tunnel_rule(svc_name, dname, e);
			} else {
				printf("-a %s -r %s %s -w %d\n",
				       svc_name,
				       dname,
				       fwd_switch(e->conn_flags),
				       e->weight);
			}
		} else if (format & FMT_STATS) {
			printf("  -> %-28s", dname);
			print_largenum(e->stats64.conns, format);
			print_largenum(e->stats64.inpkts, format);
			print_largenum(e->stats64.outpkts, format);
			print_largenum(e->stats64.inbytes, format);
			print_largenum(e->stats64.outbytes, format);
			printf("\n");
		} else if (format & FMT_RATE) {
			printf("  -> %-28s %8llu %8llu %8llu", dname,
			       e->stats64.cps,
			       e->stats64.inpps,
			       e->stats64.outpps);
			print_largenum(e->stats64.inbps, format);
			print_largenum(e->stats64.outbps, format);
			printf("\n");
		} else if (format & FMT_THRESHOLDS) {
			printf("  -> %-28s %-10u %-10u %-10u %-10u\n", dname,
			       e->u_threshold, e->l_threshold,
			       e->activeconns, e->inactconns);
		} else if (format & FMT_PERSISTENTCONN) {
			printf("  -> %-28s %-9u %-11u %-10u %-10u\n", dname,
			       e->weight, e->persistconns,
			       e->activeconns, e->inactconns);
		} else if (format & FMT_TUN_INFO) {
			char *ti = fwd_tun_info(e);

			printf("  -> %-28s %-7s %-13s %-6d %-10u %-10u\n",
			       dname, fwd_name(e->conn_flags),
			       ti ? : NA,
			       e->weight, e->activeconns, e->inactconns);

			free(ti);
		} else
			printf("  -> %-28s %-7s %-6d %-10u %-10u\n",
			       dname, fwd_name(e->conn_flags),
			       e->weight, e->activeconns, e->inactconns);
		free(dname);
	}
	free(d);
}


static void list_service(ipvs_service_t *svc, unsigned int format)
{
	ipvs_service_entry_t *entry;

	if (!(entry = ipvs_get_service(svc->fwmark, svc->af, svc->protocol,
				       svc->addr, svc->port))) {
		fprintf(stderr, "%s\n", ipvs_strerror(errno));
		exit(1);
	}

	print_title(format);
	print_service_entry(entry, format);
	free(entry);
}


static void list_all(unsigned int format)
{
	struct ip_vs_get_services *get;
	int i;

	if (!(format & FMT_RULE))
		printf("IP Virtual Server version %d.%d.%d (size=%d)\n",
		       NVERSION(ipvs_info.version), ipvs_info.size);

	if (!(get = ipvs_get_services())) {
		fprintf(stderr, "%s\n", ipvs_strerror(errno));
		exit(1);
	}

	if (!(format & FMT_NOSORT))
		ipvs_sort_services(get, ipvs_cmp_services);

	print_title(format);
	for (i = 0; i < get->num_services; i++)
		print_service_entry(&get->entrytable[i], format);
	free(get);
}


void list_timeout(void)
{
	ipvs_timeout_t *u;

	if (!(u = ipvs_get_timeout()))
		exit(1);
	printf("Timeout (tcp tcpfin udp): %d %d %d\n",
	       u->tcp_timeout, u->tcp_fin_timeout, u->udp_timeout);
	free(u);
}


static void list_daemon(void)
{
	ipvs_daemon_t *u;
	int i;

	if (!(u = ipvs_get_daemon()))
		exit(1);

	for (i = 0; i < 2; i++) {
		char *type;

		if (u[i].state & IP_VS_STATE_MASTER)
			type = "master";
		else if (u[i].state & IP_VS_STATE_BACKUP)
			type = "backup";
		else
			continue;
		printf("%s sync daemon (mcast=%s, syncid=%d",
		       type, u[i].mcast_ifn, u[i].syncid);
		if (u[i].sync_maxlen)
			printf(", maxlen=%u", u[i].sync_maxlen);
		if (u[i].mcast_af != AF_UNSPEC) {
			char addr[INET6_ADDRSTRLEN];

			if (inet_ntop(u[i].mcast_af, &u[i].mcast_group,
				      addr, sizeof(addr)))
				printf(", group=%s", addr);
		}
		if (u[i].mcast_port)
			printf(", port=%u", u[i].mcast_port);
		if (u[i].mcast_ttl)
			printf(", ttl=%u", u[i].mcast_ttl);
		printf(")\n");
	}
	free(u);
}


int host_to_addr(const char *name, struct in_addr *addr)
{
	struct hostent *host;

	if ((host = gethostbyname(name)) != NULL) {
		if (host->h_addrtype != AF_INET ||
		    host->h_length != sizeof(struct in_addr))
			return -1;
		/* warning: we just handle h_addr_list[0] here */
		memcpy(addr, host->h_addr_list[0], sizeof(struct in_addr));
		return 0;
	}
	return -1;
}


static char * addr_to_host(int af, const void *addr)
{
	struct hostent *host;

	if (af == AF_INET)
		host = gethostbyaddr((char *) addr,
				     sizeof(struct in_addr), af);
	else
		host = gethostbyaddr((char *) addr,
				     sizeof(struct in6_addr), af);

	if (host != NULL)
		return (char *) host->h_name;
	else
		return (char *) NULL;
}


static char * addr_to_anyname(int af, const void *addr)
{
	char *name;
	static char buf[INET6_ADDRSTRLEN];

	if ((name = addr_to_host(af, addr)) != NULL)
		return name;
	inet_ntop(af, addr, buf, sizeof(buf));
	return buf;
}


int service_to_port(const char *name, unsigned short proto)
{
	struct servent *service;

	if (proto == IPPROTO_TCP
	    && (service = getservbyname(name, "tcp")) != NULL)
		return ntohs((unsigned short) service->s_port);
	else if (proto == IPPROTO_UDP
		 && (service = getservbyname(name, "udp")) != NULL)
		return ntohs((unsigned short) service->s_port);
	else if (proto == IPPROTO_SCTP
		 && (service = getservbyname(name, "sctp")) != NULL)
		return ntohs((unsigned short) service->s_port);
	else
		return -1;
}


static char * port_to_service(unsigned short port, unsigned short proto)
{
	struct servent *service;

	if (proto == IPPROTO_TCP &&
	    (service = getservbyport(htons(port), "tcp")) != NULL)
		return service->s_name;
	else if (proto == IPPROTO_UDP &&
		 (service = getservbyport(htons(port), "udp")) != NULL)
		return service->s_name;
	else if (proto == IPPROTO_SCTP &&
		 (service = getservbyport(htons(port), "sctp")) != NULL)
		return service->s_name;
	else
		return (char *) NULL;
}


static char * port_to_anyname(unsigned short port, unsigned short proto)
{
	char *name;
	static char buf[10];

	if ((name = port_to_service(port, proto)) != NULL)
		return name;
	else {
		sprintf(buf, "%u", port);
		return buf;
	}
}


static char *
addrport_to_anyname(int af, const void *addr, unsigned short port,
		    unsigned short proto, unsigned int format)
{
  char *buf, pbuf[INET6_ADDRSTRLEN];

	if (!(buf=malloc(60)))
		return NULL;

	if (format & FMT_NUMERIC) {
		snprintf(buf, 60, "%s%s%s:%u",
			 af == AF_INET ? "" : "[",
			 inet_ntop(af, addr, pbuf, sizeof(pbuf)),
			 af == AF_INET ? "" : "]",
			 port);
	} else {
	  snprintf(buf, 60, "%s%s%s:%s",
		   af == AF_INET ? "" : "[",
		   addr_to_anyname(af, addr),
		   af == AF_INET ? "" : "]",
		   port_to_anyname(port, proto));
	}

	return buf;
}


static int str_is_digit(const char *str)
{
	size_t offset;
	size_t top;

	top = strlen(str);
	for (offset=0; offset<top; offset++) {
		if (!isdigit((int)*(str+offset))) {
			break;
		}
	}

	return (offset<top)?0:1;
}