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

/*
 *  Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 *  Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <locale.h>
#include <langinfo.h>
#include <search.h>
#include <tsol/label.h>
#include <errno.h>
#include <sys/tsol/tndb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <sys/signal.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <syslog.h>
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <door.h>
#include <synch.h>
#include <sys/tsol/tsyscall.h>
#include <nss_dbdefs.h>
#include <libtsnet.h>
#include <zone.h>

#include "tnd.h"

static FILE *tnlog_open(char *);
static void usage();
static void parse_opts(int, char **);
static int check_debugl(int);
static void load_tp();
static void load_tp_entry();
static void tnd_serve();
static void detachfromtty();
static void terminate();
static void noop();
static char *gettime();
static int isnumber(char *);
static void poll_now();
static int nss_get_tp();
static int nss_get_rh();
static void timer();
static void load_rh_marked();
static int rhtable_search_and_update(struct tsol_rhent *ent, int duplflag);
static int is_better_match(in_addr_t newaddr, int indx, tnrh_tlb_t *tlbt);
static int walk_cache_table(in_addr_t newaddr, char *name,
    int indx, tnd_tnrhdb_t *src);
static tnrh_tlb_t *lookup_cache_table(in_addr_t addr);
static int update_cache_table(tsol_rhent_t *ent, tnd_tnrhdb_t *src);
static void update_rh_entry(int op, struct tsol_rhent *rhentp);
static int handle_unvisited_nodes();
static in_addr_t rh_index_to_mask(uint_t masklen);
static tnrh_tlb_ipv6_t *lookup_cache_table_v6(in6_addr_t addr);
static in6_addr_t *rh_index_to_mask_v6(uint_t masklen, in6_addr_t *bitmask);
static void load_rh_marked_v6();
static int
    rhtable_search_and_update_v6(struct tsol_rhent *ent, int duplflag);
static int walk_cache_table_v6(in6_addr_t newaddr, char *name,
    int indx, tnd_tnrhdb_t *src);
static int update_cache_table_v6(tsol_rhent_t *ent, tnd_tnrhdb_t *src);
static int handle_unvisited_nodes_v6();

#ifdef DEBUG
static void print_entry(tsol_rhent_t *ent, int af);
static void print_tlbt(tnrh_tlb_t *tlbt);
static void rhtable_print();
static void cachetable_print();
static void rhtable_walk(void (*action)());
static void cachetable_print_v6();
static void rhtable_print_v6();
static void rhtable_walk_v6(void (*action)());
#endif /* DEBUG */

/*
 * The following constants and structures and the functions
 * that operate on them are similar to the ip_ire.c and ip6_ire.c
 * code in the kernel.
 */
#define	TNRH_TABLE_HASH_SIZE 256
#define	IP_ABITS 32
#define	IP_MASK_TABLE_SIZE (IP_ABITS + 1)
#define	RH_HOST_MASK (in_addr_t)0xffffffffU

#define	IPV6_ABITS 128
#define	IPV6_MASK_TABLE_SIZE (IPV6_ABITS + 1)
#define	s6_addr8 _S6_un._S6_u8
#define	s6_addr32 _S6_un._S6_u32

/*
 * Exclusive-or the 6 bytes that are likely to contain the MAC
 * address. Assumes table_size does not exceed 256.
 * Assumes EUI-64 format for good hashing.
 */
#define	TNRH_ADDR_HASH_V6(addr)				\
	(((addr).s6_addr8[8] ^ (addr).s6_addr8[9] ^	\
	(addr).s6_addr8[10] ^ (addr).s6_addr8[13] ^	\
	(addr).s6_addr8[14] ^ (addr).s6_addr8[15]) % TNRH_TABLE_HASH_SIZE)

#define	TNRH_ADDR_MASK_HASH_V6(addr, mask)	\
	((((addr).s6_addr8[8] & (mask).s6_addr8[8]) ^	\
	((addr).s6_addr8[9] & (mask).s6_addr8[9]) ^	\
	((addr).s6_addr8[10] & (mask).s6_addr8[10]) ^	\
	((addr).s6_addr8[13] & (mask).s6_addr8[13]) ^	\
	((addr).s6_addr8[14] & (mask).s6_addr8[14]) ^	\
	((addr).s6_addr8[15] & (mask).s6_addr8[15])) % TNRH_TABLE_HASH_SIZE)

/* Mask comparison: is IPv6 addr a, and'ed with mask m, equal to addr b? */
#define	V6_MASK_EQ(a, m, b)	\
	((((a).s6_addr32[0] & (m).s6_addr32[0]) == (b).s6_addr32[0]) && \
	(((a).s6_addr32[1] & (m).s6_addr32[1]) == (b).s6_addr32[1]) &&  \
	(((a).s6_addr32[2] & (m).s6_addr32[2]) == (b).s6_addr32[2]) &&  \
	(((a).s6_addr32[3] & (m).s6_addr32[3]) == (b).s6_addr32[3]))


const in6_addr_t ipv6_all_zeros = { 0, 0, 0, 0 };

/*
 * This is a table of hash tables to keep
 * all the name service entries. We don't have
 * a separate hash bucket structure, instead mantain
 * a pointer to the hash chain.
 */
tnd_tnrhdb_t **tnrh_entire_table[IP_MASK_TABLE_SIZE];
tnd_tnrhdb_t **tnrh_entire_table_v6[IPV6_MASK_TABLE_SIZE];

/* reader/writer lock for tnrh_entire_table */
rwlock_t entire_rwlp;
rwlock_t entire_rwlp_v6;


/*
 * This is a hash table which keeps fully resolved
 * tnrhdb entries <IP address, Host type>. We don't have
 * a separate hash bucket structure, instead
 * mantain a pointer to the hash chain.
 */
tnrh_tlb_t *tnrh_cache_table[TNRH_TABLE_HASH_SIZE];
tnrh_tlb_ipv6_t *tnrh_cache_table_v6[TNRH_TABLE_HASH_SIZE];

/* reader/writer lock for tnrh_cache_table */
rwlock_t cache_rwlp;
rwlock_t cache_rwlp_v6;

FILE	 *logf;
int	 debugl = 0;
int	 poll_interval = TND_DEF_POLL_TIME;
int	 delay_poll_flag = 0;

void	*tp_tree;

#define	_SZ_TIME_BUF 100
char time_buf[_SZ_TIME_BUF];

#define	cprint(s, param) { \
		register FILE *consl; \
\
		if ((consl = fopen("/dev/msglog", "w")) != NULL) { \
		    setbuf(consl, NULL); \
		    (void) fprintf(consl, "tnd: "); \
		    (void) fprintf(consl, s, param); \
		    (void) fclose(consl); \
			} \
	    }

#define	RHENT_BUF_SIZE 300
#define	TPENT_BUF_SIZE 2000

/* 128 privs * (24 bytes + 1 deliminator)= 3200 bytes + 1200 cushion */
#define	STRING_PRIVS_SIZE 4800
#define	ID_ENT_SIZE 500

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


	const ucred_t	*uc = NULL;
	const priv_set_t	*pset;
	struct sigaction act;

	/* set the locale for only the messages system (all else is clean) */
	(void) setlocale(LC_ALL, "");
#ifndef TEXT_DOMAIN			/* Should be defined by cc -D */
#define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it weren't */
#endif
	(void) textdomain(TEXT_DOMAIN);

	if (getzoneid() != GLOBAL_ZONEID) {
		syslog(LOG_ERR,	"can not run tnd from a local zone");
		exit(-1);
	}


	if (((uc = ucred_get(getpid())) == NULL) ||
	    ((pset = ucred_getprivset(uc, PRIV_EFFECTIVE)) == NULL)) {
		syslog(LOG_ERR,	"don't have privilege set");
		exit(-1);
	}

	if (!priv_ismember(pset, PRIV_SYS_NET_CONFIG)) {
		syslog(LOG_ERR,	"don't have privilege to run tnd");
		exit(-1);
	}


	/* parse command line options */
	(void) parse_opts(argc, argv);

	/*
	 * Initialize reader/writer locks. To be
	 * used within this process only.
	 */
	if ((rwlock_init(&entire_rwlp, USYNC_THREAD, 0) != 0) ||
	    (rwlock_init(&entire_rwlp_v6, USYNC_THREAD, 0) != 0) ||
	    (rwlock_init(&cache_rwlp, USYNC_THREAD, 0) != 0) ||
	    (rwlock_init(&cache_rwlp_v6, USYNC_THREAD, 0) != 0)) {
		syslog(LOG_ERR, "cannot initialize lock");
		exit(-1);
	}

	/* catch the usual termination signals for graceful exit */
	(void) sigset(SIGINT, terminate);
	(void) sigset(SIGTERM, terminate);
	(void) sigset(SIGQUIT, terminate);
	(void) sigset(SIGUSR1, noop);

	act.sa_handler = timer;
	act.sa_flags = SA_RESTART;
	(void *) sigemptyset(&act.sa_mask);
	(void *) sigaddset(&act.sa_mask, SIGALRM);
	(void *) sigaddset(&act.sa_mask, SIGHUP);
	(void *) sigaction(SIGALRM, &act, NULL);
	(void *) sigaction(SIGHUP, &act, NULL);

	if (debugl == MAX_TND_DEBUG) {
		(void) fprintf(logf, "%s : ", gettime());
		(void) fprintf(logf, gettext("tnd started. pid= %d\n"),
		    getpid());
		(void) fprintf(logf, "%s : ", gettime());
		(void) fprintf(logf,
		    gettext("max level debugging! not forking\n"));
		(void) fflush(logf);
	} else {
		detachfromtty();
	}

	if (!delay_poll_flag) {
		(void) sigprocmask(SIG_BLOCK, &act.sa_mask, NULL);
		timer();
		(void) sigprocmask(SIG_UNBLOCK, &act.sa_mask, NULL);
	}

	if (debugl != MAX_TND_DEBUG) {
		(void) sigsend(P_PID, getppid(), SIGUSR1);
	}

	(void) tnd_serve();

	/* NOT REACHED */
	return (0);
}


/*
 * Compare addresses after masking off unneeded bits.
 * We do this to handle addresses where prefix_len is
 * less than the bit length.
 */
static int
rhaddr_compar_mask(struct sockaddr_in *tp1, struct tnd_tnrhdb_c *tp2, int i)
{
	struct sockaddr_in *saddrp;
	in_addr_t tmpmask = rh_index_to_mask(i);

	saddrp = (struct sockaddr_in *)(&tp2->rh_ent.rh_address.ip_addr_v4);

#ifdef DEBUG
	(void) fprintf(logf, gettext("rhaddr_compar_mask mask = 0x%4x, \
	    tp1 = 0x%4x, tp2 = 0x%4x\n"), tmpmask, (tp1->sin_addr),
	    (saddrp->sin_addr.s_addr & tmpmask));
	(void) fprintf(logf, gettext("rhaddr_compar_mask return = %d\n"),
	    (tp1->sin_addr.s_addr == (saddrp->sin_addr.s_addr & tmpmask)));
#endif
	return (tp1->sin_addr.s_addr == (saddrp->sin_addr.s_addr & tmpmask));
}


/*
 * we use this where exact match is needed.
 */
static int
rhaddr_compar(struct sockaddr_in *tp1, struct tnd_tnrhdb_c *tp2)
{
	struct sockaddr_in *saddrp;

	saddrp = (struct sockaddr_in *)(&tp2->rh_ent.rh_address.ip_addr_v4);

#ifdef DEBUG
	(void) fprintf(logf, gettext("\t tp1 saddrp IP : %s %s\n"),
	    inet_ntoa(tp1->sin_addr), inet_ntoa(saddrp->sin_addr));
#endif

	return (tp1->sin_addr.s_addr == saddrp->sin_addr.s_addr);
}

/*
 * Compare v6 addresses after masking off unneeded bits.
 * We do this to handle addresses where prefix_len is
 * less than the bit length.
 */
static int
rhaddr_compar_mask_v6(struct sockaddr_in6 *tp1, struct tnd_tnrhdb_c *tp2, int i)
{
	struct sockaddr_in6 *saddrp;
	in6_addr_t tmpmask;

	(void) rh_index_to_mask_v6(i, &tmpmask);
	saddrp = (struct sockaddr_in6 *)(&tp2->rh_ent.rh_address.ip_addr_v6);
	return (V6_MASK_EQ(tp1->sin6_addr, tmpmask, saddrp->sin6_addr));
}

/*
 * we use this where v6 exact match is needed.
 */
static int
rhaddr_compar_v6(struct sockaddr_in6 *tp1, struct tnd_tnrhdb_c *tp2)
{
	struct sockaddr_in6 *saddrp;

	saddrp = (struct sockaddr_in6 *)(&tp2->rh_ent.rh_address.ip_addr_v6);
	return (IN6_ARE_ADDR_EQUAL(&tp1->sin6_addr, &saddrp->sin6_addr));
}

static int
get_hashvalue(in_addr_t addr)
{
	unsigned char *bp;

	bp = (unsigned char *) &addr;
	return ((bp[0] ^ bp[1] ^ bp[2] ^ bp[3]) % TNRH_TABLE_HASH_SIZE);
}

/*
 * Convert length for a mask to the mask.
 */
static in_addr_t
rh_index_to_mask(uint_t masklen)
{
	if (masklen == 0)
		return (0);
	return (htonl(RH_HOST_MASK << (IP_ABITS - masklen)));
}

/*
 * Convert length for a mask to the mask.
 * Returns the argument bitmask.
 */
static in6_addr_t *
rh_index_to_mask_v6(uint_t masklen, in6_addr_t *bitmask)
{
	uint32_t *ptr;

	*bitmask = ipv6_all_zeros;

	ptr = (uint32_t *)bitmask;
	while (masklen > 32) {
		*ptr++ = 0xffffffffU;
		masklen -= 32;
	}
	*ptr = htonl(0xffffffffU << (32 - masklen));
	return (bitmask);
}


static void
parse_opts(argc, argv)
	int argc;
	char **argv;
{
	char *logfile = TNDLOG;
	extern char *optarg;
	int c;

	while ((c = getopt(argc, argv, "d:f:p:n")) != EOF)
	    switch (c) {
	    case 'd':
		if (isnumber(optarg)) {
		    debugl = atoi(optarg);
		    if (check_debugl(debugl) == -1)
		    debugl = 1; /* default to 1 */
		} else {
		    usage();
		    exit(1);
		}
		break;
	    case 'f':
		logfile = optarg;
		break;
	    case 'p':
		if (isnumber(optarg)) {
		    poll_interval = atoi(optarg);
		    if (poll_interval == 0)
			usage();
		} else {
		    usage();
		}
		break;
	    case 'n':
		delay_poll_flag = 1;
		break;
	    case '?':
		usage();
	    }

	logf = tnlog_open(logfile);
}

static int
check_debugl(debug_level)
	int debug_level;
{
	if (debug_level > MAX_TND_DEBUG) {
	    if ((debugl > 0) && (logf != NULL)) {
		(void) fprintf(logf, "%s : ", gettime());
		(void) fprintf(logf,
		    gettext("invalid debug level: %d, not changed!\n"),
			debug_level);
		(void) fflush(logf);
	    }
	    cprint("invalid debug level: %d, not changed!\n",
		debug_level);
	    return (-1);
	}
	return (0);
}

static FILE *
tnlog_open(logfile)
	char *logfile;
{
	FILE *fp;

	if ((fp = fopen(logfile, "a")) == NULL) {
		syslog(LOG_ERR, "unable to open logfile %s",
			logfile);
		exit(-1);
	}
	(void) fprintf(fp, "%s : ", gettime());
	(void) fprintf(fp, gettext("tnd starting\n"));

	return (fp);
}

static void
detachfromtty()
{
	pid_t tnd_pid;

	(void) close(0);
	(void) close(1);
	(void) close(2);
	switch (tnd_pid = fork()) {
	case (pid_t)-1:
		if (debugl && (logf != NULL)) {
			(void) fprintf(logf, "%s : ", gettime());
			(void) fprintf(logf,
			    gettext("fork() failed: %s\n"), strerror(errno));
			(void) fflush(logf);
		}
		cprint("fork() failed: %s\n", strerror(errno));
		break;
	case 0:
		break;
	default:
		if (debugl && (logf != NULL)) {
			(void) fprintf(logf, "%s : ", gettime());
			(void) fprintf(logf,
			    gettext("tnd started. pid= %d\n"), tnd_pid);
			(void) fflush(logf);
		}
		/*
		 * Suspend parent till child signals it. We catch the signal
		 * in order to return correct exit value.
		 */

		(void) pause();
		exit(0);
	}
	(void) setsid();
	(void) open("/dev/null", O_RDWR, 0);
	(void) dup(0);
	(void) dup(0);
}

static void
usage()
{
	(void) fprintf(stderr, gettext(
	    "Usage:\n\ttnd [-d debug-level][-f debug-file]"
	    "[-p poll-interval]\n"));

	exit(1);
}

static int
isnumber(s)
char *s;
{
	register int c;

	/* LINTED */
	while (c = *s++)
		if (!isdigit(c))
			return (0);
	return (1);
}


/*
 * match any entry in any tree
 *	used in tree removal
 */
/* ARGSUSED */
static int
any_compar(const void *v1, const void *v2)
{
	return (0);
}

static int
tp_compar(const void *v1, const void *v2)
{
	struct tnd_tnrhtp_c	*tp1 = (struct tnd_tnrhtp_c *)v1;
	struct tnd_tnrhtp_c	*tp2 = (struct tnd_tnrhtp_c *)v2;
	return (strcmp(tp1->tp_ent.name, tp2->tp_ent.name));
}

/*
 * Build tree of tp entries, tossing duplicates
 */
static int
nss_get_tp()
{
	tsol_tpent_t tp; /* to store result */
	tsol_tpent_t *tpp;
	struct tnd_tnrhtp_c *new, **old;
	int count = 0;

	tpp = &tp;

	tsol_settpent(1);

	while ((tpp = (tsol_tpent_t *)tsol_gettpent()) != NULL) {
		if ((new = (struct tnd_tnrhtp_c *)
		    calloc(1, sizeof (struct tnd_tnrhtp_c))) == NULL)
			continue;
		(void) memcpy(&new->tp_ent, tpp, sizeof (tp));
		old = (struct tnd_tnrhtp_c **)tsearch(new, &tp_tree, tp_compar);
		if (*old != new)
			free(new);
		else
			count++;
	}
	tsol_endtpent();

	return (count);
}

/* load tp ents into kernel */
static void
load_tp()
{
	twalk(tp_tree, load_tp_entry);
}


static void
/* LINTED */
load_tp_entry(struct tnd_tnrhtp_c **tppp, VISIT visit, int level)
{
	struct tnd_tnrhtp_c *tpp;

	if (!(visit == postorder || visit == leaf))
		return;

	tpp = *tppp;
	if (tnrhtp(TNDB_LOAD, &tpp->tp_ent)) {
		if (debugl && (logf != NULL)) {
			(void) fprintf(logf, "%s : ", gettime());
			(void) fprintf(logf, gettext("tnrhtp() failed 0: %s\n"),
			    strerror(errno));
			(void) fprintf(logf,
			    gettext("load of remote-host template "
			    "%s into kernel cache failed\n"),
			    tpp->tp_ent.name);
			(void) fflush(logf);
		}
		cprint("tnrhtp() failed here 1: %s\n", strerror(errno));
	}
}

static void
tp_flush_cache()
{
	struct tnd_tnrhtp_c	dummy;
	struct tnd_tnrhtp_c	*tp;

	while (tp = tfind(&dummy, tp_tree, any_compar)) {
		(void) tdelete(tp, &tp_tree, tp_compar);
		free(tp);
	}
}

/*
 * Build/update the table of rh entries from the
 * name service sources, files, ldap etc.
 */
static int
nss_get_rh()
{
	int found_entry = 0;
	int count = 0;
	int newflag = 0;
	struct tsol_rhent rh; /* to store result */
	struct tsol_rhent *rhp;
	tsol_tpent_t tp;
	sa_family_t af;
	int v6cnt = 0;

	rhp = &rh;

	tsol_setrhent(1);
	while ((rhp = (struct tsol_rhent *)
	    tsol_getrhent()) != NULL) {
		/*
		 * Check if this is a known template name
		 * Entries with missing template in kernel will be logged
		 * and not added to cache.
		 */

		(void) fprintf(logf, gettext("getrhent template name: %s\n"),
		    rhp->rh_template);

		(void) strncpy(tp.name, rhp->rh_template, TNTNAMSIZ - 1);
		if (tnrhtp(TNDB_GET, &tp) != 0) {
			if (debugl && (logf != NULL))
				(void) fprintf(logf,
				    gettext("Unknown template name: %s\n"),
				    rhp->rh_template);
			cprint(gettext("Unknown template name: %s\n"),
			    rhp->rh_template);
			continue;
		}
		found_entry++;		/* found a valid tnrhdb entry */
		af = rhp->rh_address.ta_family;

		if (af == AF_INET) {
#ifdef DEBUG
			(void) fprintf(logf, gettext("nss_get_rh() v4\n"));
#endif
			(void) rw_wrlock(&entire_rwlp);
			(void) rw_wrlock(&cache_rwlp);

			/*
			 * Both cache table and entire table can be modified
			 * by this function. So, get both locks.
			 */
			newflag = rhtable_search_and_update(rhp, 1);

			(void) rw_unlock(&cache_rwlp);
			(void) rw_unlock(&entire_rwlp);
		} else if (af == AF_INET6) {
#ifdef DEBUG
			(void) fprintf(logf, gettext("nss_get_rh() v6\n"));
#endif
			v6cnt++;
			(void) rw_wrlock(&entire_rwlp_v6);
			(void) rw_wrlock(&cache_rwlp_v6);

			/*
			 * Both cache table and entire table can be modified
			 * by this function. So, get both locks.
			 */
			newflag = rhtable_search_and_update_v6(rhp, 1);

			(void) rw_unlock(&cache_rwlp_v6);
			(void) rw_unlock(&entire_rwlp_v6);
		}
		if (newflag)
			count++;
	}
	tsol_endrhent();

	/*
	 * If the first tsol_getrhent() failed, we bail out and
	 * try again at the next poll interval, just in case the
	 * name service was not reachable the first time.
	 */
	if (!found_entry) {
#ifdef	DEBUG
		if (logf != NULL)
			(void) fprintf(logf,
			    gettext("Unable to contact ldap server?\n"));
#endif
		return (count);
	}

	(void) rw_wrlock(&entire_rwlp);
	(void) rw_wrlock(&cache_rwlp);
	/*
	 * Handle deletions in the name service entries
	 * Both cache table and entire table can be modified
	 * by this function. So, get both locks.
	 */
	count += handle_unvisited_nodes();

	(void) rw_unlock(&cache_rwlp);
	(void) rw_unlock(&entire_rwlp);

	if (v6cnt > 0) {
		(void) rw_wrlock(&entire_rwlp_v6);
		(void) rw_wrlock(&cache_rwlp_v6);
		/*
		 * Handle deletions in the name service entries
		 * Both cache table and entire table can be modified
		 * by this function. So, get both locks.
		 */
		count += handle_unvisited_nodes_v6();

		(void) rw_unlock(&cache_rwlp_v6);
		(void) rw_unlock(&entire_rwlp_v6);
	}

	return (count);
}

/*
 * Check if any deletions in  the name service tables
 * affect the cache entries. We need to do this
 * in order to not flush the entrie kernel tnrhdb
 * cache every time we poll the name services.
 */
static int
handle_unvisited_nodes()
{
	int i, j, cnt = 0;
	tnrh_tlb_t *tlbt;
	tnd_tnrhdb_t *rhent, *prev;

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++)
		if ((tlbt = tnrh_cache_table[i]) != NULL)
			do {
				if (tlbt->src->visited == 0) {
					/*
					 * Mark for deletion of both our cache
					 * entry and the kernel cache entry.
					 */
					tlbt->reload = TNDB_DELETE;
					cnt++;
				}

				tlbt = tlbt->next;
			} while (tlbt != NULL);

	/*
	 * Remove any unvisited nodes. This can
	 * happen if they are not in use by any cache entry. Then,
	 * mark all nodes in entire_table, un-visited, for next iteration.
	 */

	for (i = 0; i <= IP_ABITS; i++) {
		if (tnrh_entire_table[i] == NULL)
			continue;

		for (j = 0; j < TNRH_TABLE_HASH_SIZE; j++) {
			prev = rhent = tnrh_entire_table[i][j];

			while (rhent != NULL) {
				if (rhent->visited == 0) {
					/*
					 * Check if start node
					 */
					if (rhent == tnrh_entire_table[i][j]) {
						prev = tnrh_entire_table[i][j] =
						    rhent->rh_next;
					} else {
						/* bypass the deleted node */
						prev->rh_next = rhent->rh_next;
						prev = prev->rh_next;
					}

					free(rhent);

					if (prev == NULL)
						break;
					else {
						rhent = prev;
						continue;
					}
				} else
					rhent->visited = 0;

				prev = rhent;
				rhent = rhent->rh_next;
			}
		}
	}

	return (cnt);
}

/*
 * Check if any deletions in  the name service tables
 * affect the cache entries. We need to do this
 * in order to not flush the entrie kernel tnrhdb
 * cache every time we poll the name services.
 */
static int
handle_unvisited_nodes_v6()
{
	int i, j, cnt = 0;
	tnrh_tlb_ipv6_t *tlbt;
	tnd_tnrhdb_t *rhent, *prev;

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++)
	if ((tlbt = tnrh_cache_table_v6[i]) != NULL)
	do {
		if (tlbt->src->visited == 0) {
			/*
			 * Mark for deletion of both our cache entry
			 * and the kernel cache entry.
			 */
			tlbt->reload = TNDB_DELETE;
			cnt++;
		}

		tlbt = tlbt->next;
	} while (tlbt != NULL);

	/*
	 * Remove any unvisited nodes. This can
	 * happen if they are not in use by any cache entry. Then,
	 * mark all nodes in entire_table, un-visited, for next iteration.
	 */

	for (i = 0; i <= IPV6_ABITS; i++) {
	if (tnrh_entire_table_v6[i] == NULL)
		continue;

	for (j = 0; j < TNRH_TABLE_HASH_SIZE; j++) {
		prev = rhent = tnrh_entire_table_v6[i][j];

		while (rhent != NULL) {
		if (rhent->visited == 0) {	/* delete the node */
			/* Check if start node */
			if (rhent == tnrh_entire_table_v6[i][j]) {
				prev = tnrh_entire_table_v6[i][j] =
				    rhent->rh_next;
			} else {
				/* bypass the deleted node */
				prev->rh_next = rhent->rh_next;
				prev = prev->rh_next;
			}

			free(rhent);
			if (prev == NULL)
				break;
			else {
				rhent = prev;
				continue;
			}
		} else
			rhent->visited = 0;

		prev = rhent;
		rhent = rhent->rh_next;
		}
	}
	}

	return (cnt);
}


/*
 * Search the hash chain for the address. If not found,
 * add the entry to the hash table. If necessary,
 * construct the hash table.
 * If the rh entry is in table, we may update its template name
 */
static int
rhtable_search_and_update(struct tsol_rhent *ent, int duplflag)
{
	struct sockaddr_in *saddrp;
	unsigned char hash;
	tnd_tnrhdb_t *rhent;
	int i;
	int rflag = 1;

	struct tnd_tnrhdb_c *new;

	saddrp = (struct sockaddr_in *)&ent->rh_address.ip_addr_v4;
	hash = (unsigned char) get_hashvalue(saddrp->sin_addr.s_addr);
	i = ent->rh_prefix;

#ifdef DEBUG
	(void) fprintf(logf, gettext("\trhtable_search_and_update IP address:\
		%s\n"), inet_ntoa(saddrp->sin_addr));
#endif

	if (tnrh_entire_table[i] == NULL) {
		if ((tnrh_entire_table[i] = (tnd_tnrhdb_t **)calloc(
		    TNRH_TABLE_HASH_SIZE, sizeof (tnd_tnrhdb_t *))) == NULL) {
			return (0);
		}
	}

	rhent = tnrh_entire_table[i][hash];
#ifdef DEBUG
	(void) fprintf(logf, gettext("\tsearch_and_update i = %d hash = %d\n"),
	    i, hash);
	if (rhent != NULL) {
		(void) fprintf(logf, gettext("\trhent visited  = %d\n"),
		    rhent->visited);
		print_entry(&rhent->rh_ent, AF_INET);
	} else {
		(void) fprintf(logf, gettext("\tsearch_and_update null\n"));
	}
#endif
	while (rhent != NULL) {
		if (rhaddr_compar(saddrp, rhent) == 1) {
			/* Check if this is a duplicate entry */
			if ((rhent->visited == 1) && duplflag)
				return (0);

			if (duplflag)
				rhent->visited = 1;

			if (strcmp(ent->rh_template,
			    rhent->rh_ent.rh_template) != 0) {
				/*
				 * Template is changed in the name service.
				 * Use the new template.
				 */
				(void) strcpy(rhent->rh_ent.rh_template,
				    ent->rh_template);
				/*
				 * Check if this modified entry
				 * affects the cache table.
				 */
				rflag = update_cache_table(ent, rhent);
				return (rflag);
			} else
				return (0);
		}
		rhent = rhent->rh_next;
	}

	/* Not found. Add the entry */
	new = (struct tnd_tnrhdb_c *)calloc(1,
	    sizeof (struct tnd_tnrhdb_c));
	if (new == NULL)
		return (0);
	(void) memcpy(&new->rh_ent, ent, sizeof (struct tsol_rhent));
	if (duplflag)
		new->visited = 1;	/* Mark all new nodes visited */

	/* linked list. Insert in the beginning */
	new->rh_next = tnrh_entire_table[i][hash];
	tnrh_entire_table[i][hash] = new;
#ifdef DEBUG
	(void) fprintf(logf, gettext("rhtable added i = %d, hash = %d\n"),
	    i, hash);
#endif

	/* Check if the new entry affects the cache table */
	rflag = update_cache_table(ent, new);

#ifdef DEBUG
	(void) fprintf(logf, gettext("search_and_update rflag=%d\n"), rflag);
#endif
	return (rflag);
}

/*
 * Search the hash chain for the address. If not found,
 * add the entry to the hash table. If necessary,
 * construct the hash table.
 */
static int
rhtable_search_and_update_v6(struct tsol_rhent *ent, int duplflag)
{
	struct sockaddr_in6 *saddrp;
	unsigned char hash;
	tnd_tnrhdb_t *rhent;
	int i;
	int rflag = 1;

	struct tnd_tnrhdb_c *new;
	in6_addr_t tmpmask6;

	saddrp = (struct sockaddr_in6 *)&ent->rh_address.ip_addr_v6;
	i = ent->rh_prefix;
	(void) rh_index_to_mask_v6(i, &tmpmask6);
	hash = (unsigned char) TNRH_ADDR_MASK_HASH_V6(saddrp->sin6_addr,
	    tmpmask6);

	if (tnrh_entire_table_v6[i] == NULL) {
		if ((tnrh_entire_table_v6[i] = (tnd_tnrhdb_t **)calloc(
		    TNRH_TABLE_HASH_SIZE, sizeof (tnd_tnrhdb_t *))) == NULL) {
			return (0);
		}
	}

	rhent = tnrh_entire_table_v6[i][hash];
	while (rhent != NULL) {
		if (rhaddr_compar_v6(saddrp, rhent) == 1) {
			/* Check if this is a duplicate entry */
			if ((rhent->visited == 1) && duplflag)
				return (0);

			if (duplflag)
				rhent->visited = 1;

			if (strcmp(ent->rh_template,
			    rhent->rh_ent.rh_template) != 0) {
				/*
				 * Template is changed in the name service.
				 * Use the new template.
				 */
				(void) strcpy(rhent->rh_ent.rh_template,
				    ent->rh_template);
				/*
				 * Check if this modified entry
				 * affects the cache table.
				 */
				rflag = update_cache_table_v6(ent, rhent);
				return (rflag);
			} else
				return (0);
		}
		rhent = rhent->rh_next;
	}

	/* Not found. Add the entry */
	new = (struct tnd_tnrhdb_c *)calloc(1, sizeof (struct tnd_tnrhdb_c));
	if (new == NULL)
		return (0);
	(void) memcpy(&new->rh_ent, ent, sizeof (struct tsol_rhent));
	if (duplflag)
		new->visited = 1;	/* Mark all new nodes visited */

	/* linked list. Insert in the beginning */
	new->rh_next = tnrh_entire_table_v6[i][hash];
	tnrh_entire_table_v6[i][hash] = new;

	/* Check if the new entry affects the cache table */
	rflag = update_cache_table_v6(ent, new);

	return (rflag);
}

/*
 * The array element i points to the hash table.
 * Search the hash chain for the address.
 */
static struct tnd_tnrhdb_c *
rhtable_lookup(struct sockaddr_in *saddrp, int i)
{
	unsigned char hash;
	tnd_tnrhdb_t *rhent;

	if (tnrh_entire_table[i] == NULL)
		return (NULL);

	hash = (unsigned char) get_hashvalue(saddrp->sin_addr.s_addr);
	rhent = tnrh_entire_table[i][hash];

#ifdef DEBUG
	(void) fprintf(logf, gettext("rhtable_lookup i = %d, hash = %d\n"),
	    i, hash);
#endif

	while (rhent != NULL) {
#ifdef DEBUG
	struct sockaddr_in *saddrp2;
	saddrp2 = (struct sockaddr_in *)(&rhent->rh_ent.rh_address.ip_addr_v4);
	(void) fprintf(logf, gettext("rhtable_lookup addr = %s, tmpl = %s\n"),
	    inet_ntoa(saddrp2->sin_addr), rhent->rh_ent.rh_template);
#endif
		if (rhaddr_compar_mask(saddrp, rhent, i) == 1)
			return (rhent);
		rhent = rhent->rh_next;
	}

#ifdef DEBUG
	(void) fprintf(logf, gettext("\trhtable_lookup failed\n"));
#endif

	/* Not found */
	return (NULL);
}

/*
 * The array element i points to the hash table.
 * Search the hash chain for the address.
 */
static struct tnd_tnrhdb_c *
rhtable_lookup_v6(struct sockaddr_in6 *saddrp, in6_addr_t mask, int i)
{
	unsigned char hash;
	tnd_tnrhdb_t *rhent;

	if (tnrh_entire_table_v6[i] == NULL)
		return (NULL);

	hash = (unsigned char) TNRH_ADDR_MASK_HASH_V6(saddrp->sin6_addr, mask);
	rhent = tnrh_entire_table_v6[i][hash];

	while (rhent != NULL) {
		if (rhaddr_compar_mask_v6(saddrp, rhent, i) == 1)
			return (rhent);
		rhent = rhent->rh_next;
	}

	/* Not found */
	return (NULL);
}

void
add_cache_entry(in_addr_t addr, char *name, int indx,
    tnd_tnrhdb_t *src)
{
	unsigned char hash;
	tnrh_tlb_t *tlbt;

	hash = (unsigned char) get_hashvalue(addr);

	/* Look if some other thread already added this entry */
	if (lookup_cache_table(addr) != NULL)
		return;
#ifdef DEBUG
	(void) fprintf(logf, gettext("\tenter add_cache_entry\n"));
#endif
	if ((tlbt = (tnrh_tlb_t *)calloc(1, sizeof (tnrh_tlb_t))) == NULL)
		return;
	tlbt->addr = addr;
	(void) strncpy(tlbt->template_name, name, TNTNAMSIZ-1);
	tlbt->masklen_used = indx;
	tlbt->reload = TNDB_LOAD;
	tlbt->src = src;

#ifdef DEBUG
	(void) fprintf(logf, gettext("adding cache entry\n"));
	print_tlbt(tlbt);
#endif
	/* Add to the chain */
	if (tnrh_cache_table[hash] == NULL) {
		tnrh_cache_table[hash] = tlbt;
	} else {
		/* Add in the beginning */
		tlbt->next = tnrh_cache_table[hash];
		tnrh_cache_table[hash] = tlbt;
	}
}

static tnrh_tlb_t *
lookup_cache_table(in_addr_t addr)
{
	tnrh_tlb_t *tlbt = NULL;
	unsigned char hash;

	hash = (unsigned char) get_hashvalue(addr);
	tlbt = tnrh_cache_table[hash];
	while (tlbt != NULL) {
		if (addr == tlbt->addr)
			break;
		tlbt = tlbt->next;
	}
	return (tlbt);
}

static void
add_cache_entry_v6(in6_addr_t addr, char *name, int indx,
				tnd_tnrhdb_t *src)
{
	unsigned char hash;
	tnrh_tlb_ipv6_t *tlbt;

	hash = (unsigned char) TNRH_ADDR_HASH_V6(addr);

	/* Look if some other thread already added this entry */
	if (lookup_cache_table_v6(addr) != NULL)
		return;

	if ((tlbt = (tnrh_tlb_ipv6_t *)calloc(1,
	    sizeof (tnrh_tlb_ipv6_t))) == NULL)
		return;
	(void) memcpy(&tlbt->addr, &addr, sizeof (in6_addr_t));
	(void) strncpy(tlbt->template_name, name, TNTNAMSIZ-1);
	tlbt->masklen_used = indx;
	tlbt->reload = TNDB_LOAD;
	tlbt->src = src;

	/* Add to the chain */
	if (tnrh_cache_table_v6[hash] == NULL) {
		tnrh_cache_table_v6[hash] = tlbt;
	} else {
		/* Add in the beginning */
		tlbt->next = tnrh_cache_table_v6[hash];
		tnrh_cache_table_v6[hash] = tlbt;
	}
}

static tnrh_tlb_ipv6_t *
lookup_cache_table_v6(in6_addr_t addr)
{
	tnrh_tlb_ipv6_t *tlbt = NULL;
	unsigned char hash;

	hash = (unsigned char) TNRH_ADDR_HASH_V6(addr);
	tlbt = tnrh_cache_table_v6[hash];
	while (tlbt != NULL) {
		if (IN6_ARE_ADDR_EQUAL(&addr, &tlbt->addr))
			break;
		tlbt = tlbt->next;
	}
	return (tlbt);
}


/*
 * Walk the cache table and check if this IP address/address prefix
 * will be a better match for an existing entry in the cache.
 * will add cache if not already exists
 */
static int
update_cache_table(tsol_rhent_t *ent, tnd_tnrhdb_t *src)
{
	int i;
	char result[TNTNAMSIZ];
	in_addr_t tmpmask;
	in_addr_t addr;
	struct sockaddr_in *saddrp;
	tnrh_tlb_t *tlbt;
	struct tnd_tnrhdb_c	*rhp;
	int rflag = 0;

	saddrp = (struct sockaddr_in *)&ent->rh_address.ip_addr_v4;
	addr = saddrp->sin_addr.s_addr;

	(void) rw_rdlock(&cache_rwlp);
	tlbt = lookup_cache_table(addr);
	(void) rw_unlock(&cache_rwlp);

	if (tlbt == NULL) {
		(void) rw_rdlock(&entire_rwlp);
		for (i = (IP_MASK_TABLE_SIZE - 1); i >= 0; i--) {
#ifdef DEBUG
			(void) fprintf(logf, "update_cache_table i = %d\n", i);
#endif
			if (tnrh_entire_table[i] == NULL)
				continue;

			tmpmask = rh_index_to_mask(i);
			saddrp->sin_addr.s_addr &= tmpmask;
#ifdef DEBUG
			(void) fprintf(logf,
			    "update_cache_table found i = %d\n", i);
			(void) fprintf(logf, "\ti = %d, tmpmask = 0x%4x\n",
			    i, tmpmask);
#endif
			rhp = (struct tnd_tnrhdb_c *)rhtable_lookup(saddrp, i);
			if (rhp != NULL) {
				(void) strcpy(result, rhp->rh_ent.rh_template);
				/* Add this result to the cache also */
				(void) rw_wrlock(&cache_rwlp);
				add_cache_entry(addr, result, i, rhp);
				rflag++;
				(void) rw_unlock(&cache_rwlp);
				break;
			} else {
#ifdef DEBUG
				(void) fprintf(logf,
				    "rhtable_lookup return null !!");
#endif
			}
		}
		(void) rw_unlock(&entire_rwlp);
	}

	rflag += walk_cache_table(addr, ent->rh_template, ent->rh_prefix, src);
	return (rflag);
}

/*
 * Walk the cache table and check if this IP address/address prefix
 * will be a better match for an existing entry in the cache.
 */
static int
update_cache_table_v6(tsol_rhent_t *ent, tnd_tnrhdb_t *src)
{
	int i;
	char result[TNTNAMSIZ];
	in6_addr_t addr;
	struct sockaddr_in6 *saddrp;
	tnrh_tlb_ipv6_t *tlbt;
	struct tnd_tnrhdb_c	*rhp;
	in6_addr_t tmpmask6;
	int rflag = 0;

	saddrp = (struct sockaddr_in6 *)&ent->rh_address.ip_addr_v6;
	(void) memcpy(&addr, &saddrp->sin6_addr, sizeof (in6_addr_t));

	/* Look in the cache first */
	(void) rw_rdlock(&cache_rwlp);
	tlbt = lookup_cache_table_v6(addr);
	(void) rw_unlock(&cache_rwlp);


	if (tlbt == NULL) {
		(void) rw_rdlock(&entire_rwlp_v6);
		for (i = (IPV6_MASK_TABLE_SIZE - 1); i >= 0; i--) {
			if (tnrh_entire_table_v6[i] == NULL)
				continue;
			(void) rh_index_to_mask_v6(i, &tmpmask6);
			rhp = (struct tnd_tnrhdb_c *)
			    rhtable_lookup_v6(saddrp, tmpmask6, i);
			if (rhp != NULL) {
				(void) strcpy(result, rhp->rh_ent.rh_template);
				/* Add this result to the cache also */
				(void) rw_wrlock(&cache_rwlp_v6);
				add_cache_entry_v6(addr, result, i, rhp);
				rflag++;
				(void) rw_unlock(&cache_rwlp_v6);
				break;
			}
		}
		(void) rw_unlock(&entire_rwlp_v6);
	}

	rflag += walk_cache_table_v6(addr, ent->rh_template,
	    ent->rh_prefix, src);
	return (rflag);
}


/*
 * Check if this prefix addr will be a better match
 * for an existing entry.
 */
static int
is_better_match(in_addr_t newaddr, int indx, tnrh_tlb_t *tlbt)
{
	if (tlbt->masklen_used <= indx) {
		in_addr_t tmpmask = rh_index_to_mask(indx);

		if ((newaddr) == (tlbt->addr & tmpmask))
			return (1);
	}

	return (0);
}

/*
 * Walk the cache table and update entries if needed.
 * Mark entries for reload to kernel, if somehow their
 * template changed.
 * why is_better_match() is called???
 */
static int
walk_cache_table(in_addr_t newaddr, char *name, int indx, tnd_tnrhdb_t *src)
{
	int i;
	tnrh_tlb_t *tlbt;
	int rflag = 0;

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++) {
		tlbt = tnrh_cache_table[i];

		while (tlbt != NULL) {
			if (is_better_match(newaddr, indx, tlbt)) {
				tlbt->masklen_used = indx;
				tlbt->src = src;
				/*
				 * Reload to the kernel only if the
				 * host type changed. There is no need
				 * to load, if only the mask used has changed,
				 * since the kernel does not need that
				 * information.
				 */
				if (strcmp(name, tlbt->template_name) != 0) {
					(void) strncpy(tlbt->template_name,
					    name, TNTNAMSIZ-1);
					tlbt->reload = TNDB_LOAD;
					rflag ++;
				}
			}

			tlbt = tlbt->next;
		}
	}
#ifdef DEBUG
	(void) fprintf(logf, gettext("walk_cache_table rflag=%d\n"), rflag);
#endif
	return (rflag);
}

/*
 * Check if this prefix addr will be a better match
 * for an existing entry.
 */
static int
is_better_match_v6(in6_addr_t newaddr, int indx, tnrh_tlb_ipv6_t *tlbt)
{
	in6_addr_t tmpmask;

	if (tlbt->masklen_used <= indx) {
		(void) rh_index_to_mask_v6(indx, &tmpmask);

		if (V6_MASK_EQ(newaddr, tmpmask, tlbt->addr))
			return (1);
	}

	return (0);
}


/*
 * Walk the cache table and update entries if needed.
 * Mark entries for reload to kernel, if somehow their
 * template changed.
 */
static int
walk_cache_table_v6(in6_addr_t newaddr, char *name, int indx, tnd_tnrhdb_t *src)
{
	int i;
	tnrh_tlb_ipv6_t *tlbt;
	int rflag = 0;

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++) {
		tlbt = tnrh_cache_table_v6[i];

		while (tlbt != NULL) {
			if (is_better_match_v6(newaddr, indx, tlbt)) {
				tlbt->masklen_used = indx;
				tlbt->src = src;
				/*
				 * Reload to the kernel only if the
				 * host type changed. There is no need
				 * to load, if only the mask used has changed,
				 * since the kernel does not need that
				 * information.
				 */
				if (strcmp(name, tlbt->template_name) != 0) {
					(void) strncpy(tlbt->template_name,
					    name, TNTNAMSIZ-1);
					tlbt->reload = TNDB_LOAD;
					rflag ++;
				}
			}

			tlbt = tlbt->next;
		}
	}

	return (rflag);
}

/*
 * load/delete marked rh ents into kernel
 * depending on the reload flag by invoking tnrh().
 * It will mark other entries as TNDB_NOOP
 */
static void
load_rh_marked()
{
	int i;
	tnrh_tlb_t *tlbt, *prev;
	struct tsol_rhent rhentp;

	(void) memset((char *)&rhentp, '\0', sizeof (rhentp));

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++) {

		prev = tlbt = tnrh_cache_table[i];

		while (tlbt != NULL) {
			if ((tlbt->reload == TNDB_LOAD) ||
			    (tlbt->reload == TNDB_DELETE)) {
			/*
			 * We have to call tnrh() with tsol_rhent argument.
			 * Construct such a struct from the tlbt struct we have.
			 */
				rhentp.rh_address.ip_addr_v4.sin_addr.s_addr =
				    tlbt->addr;
				rhentp.rh_address.ip_addr_v4.sin_family =
				    AF_INET;
				rhentp.rh_prefix = tlbt->masklen_used;
				(void) strcpy(rhentp.rh_template,
				    tlbt->template_name);

#ifdef DEBUG
				(void) fprintf(logf, "load op =%d\n",
				    tlbt->reload);
				print_tlbt(tlbt);
#endif
				update_rh_entry(tlbt->reload, &rhentp);

				if (tlbt->reload == TNDB_DELETE) {
					if (tlbt == tnrh_cache_table[i]) {
						tnrh_cache_table[i] =
						    tlbt->next;
						prev = tnrh_cache_table[i];
					} else {
						prev->next = tlbt->next;
						prev = prev->next;
					}

					free(tlbt);
					if (prev == NULL)
						break;
					else {
						tlbt = prev;
						continue;
					}
				}
				tlbt->reload = TNDB_NOOP;
			}

			prev = tlbt;
			tlbt = tlbt->next;
		}
	}

}

/* load marked rh ents into kernel */
static void
load_rh_marked_v6()
{
	int i;
	tnrh_tlb_ipv6_t *tlbt, *prev;
	struct tsol_rhent rhentp;

	(void) memset((char *)&rhentp, '\0', sizeof (rhentp));

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++) {
		prev = tlbt = tnrh_cache_table_v6[i];

		while (tlbt != NULL) {
		if ((tlbt->reload == TNDB_LOAD) ||
		    (tlbt->reload == TNDB_DELETE)) {
			/*
			 * We have to call tnrh() with tsol_rhent argument.
			 * Construct such a struct from the tlbt struct we have.
			 */
			(void) memcpy(&rhentp.rh_address.ip_addr_v6.sin6_addr,
			    &tlbt->addr, sizeof (in6_addr_t));
			rhentp.rh_address.ip_addr_v6.sin6_family = AF_INET6;
			rhentp.rh_prefix = tlbt->masklen_used;
			(void) strcpy(rhentp.rh_template, tlbt->template_name);

			update_rh_entry(tlbt->reload, &rhentp);

			if (tlbt->reload == TNDB_DELETE) {
				if (tlbt == tnrh_cache_table_v6[i]) {
					tnrh_cache_table_v6[i] =
					    tlbt->next;
					prev = tnrh_cache_table_v6[i];
				} else {
					prev->next = tlbt->next;
					prev = prev->next;
				}

				free(tlbt);
				if (prev == NULL)
					break;
				else {
					tlbt = prev;
					continue;
				}
			}
			tlbt->reload = TNDB_NOOP;
		}

		prev = tlbt;
		tlbt = tlbt->next;
	}
	}

}

/*
 * Does the real load/delete for the entry depending on op code.
 */

static void
update_rh_entry(int op, struct tsol_rhent *rhentp)
{
#ifdef DEBUG
	(void) fprintf(logf, gettext("\t###update_rh_entry op = %d\n"), op);
	print_entry(rhentp, AF_INET);
#endif
	if (tnrh(op, rhentp) != 0) {
		if (debugl && (logf != NULL)) {
			(void) fprintf(logf, "%s : ", gettime());
			(void) fprintf(logf, gettext("tnrh() failed: %s\n"),
			    strerror(errno));
			if (op == TNDB_LOAD)
			(void) fprintf(logf,
			    gettext("load of remote host database "
			    "%s into kernel cache failed\n"),
			    rhentp->rh_template);
			if (op == TNDB_DELETE)
			(void) fprintf(logf,
			    gettext("delete of remote host database "
			    "%s from kernel cache failed\n"),
			    rhentp->rh_template);
			(void) fflush(logf);
		}
		cprint("tnrh() failed..: %s\n", strerror(errno));
	}
}

static void
timer()
{
	poll_now();
	(void) alarm(poll_interval);
}

#define	max(a, b)	((a) > (b) ? (a) : (b))

static void
poll_now()
{

	(void) fprintf(logf, "enter poll_now at %s \n", gettime());
	(void) fflush(logf);

	if (nss_get_tp() > 0) {
		load_tp();
		tp_flush_cache();
	}

#ifdef DEBUG
	(void) fprintf(logf, "now search for tnrhdb update %s \n", gettime());
#endif

	if (nss_get_rh() > 0) {
		if (logf != NULL) {
			(void) fprintf(logf, "tnrhdb needs update %s \n",
			    gettime());
		}

		(void) rw_wrlock(&cache_rwlp);
		/* This function will cleanup cache table */
		load_rh_marked();
		(void) rw_unlock(&cache_rwlp);

		(void) rw_wrlock(&cache_rwlp_v6);
		/* This function will cleanup cache table */
		load_rh_marked_v6();
		(void) rw_unlock(&cache_rwlp_v6);
	}

#ifdef DEBUG
	if (logf != NULL) {
		cachetable_print();
		cachetable_print_v6();

		(void) fprintf(logf, "rh table begin\n");
		rhtable_print();
		rhtable_print_v6();
		(void) fprintf(logf, "rh table end \n");
		(void) fprintf(logf, "-------------------------\n\n");
		(void) fflush(logf);
	}
#endif
}

static void
tnd_serve()
{
	for (;;) {
		(void) pause();
	}
}

static void
terminate()
{
	if (debugl && (logf != NULL)) {
		(void) fprintf(logf, "%s : ", gettime());
		(void) fprintf(logf, gettext("tnd terminating on signal.\n"));
		(void) fflush(logf);
	}
	exit(1);
}

static void
noop()
{
}

static char *
gettime()
{
	time_t now;
	struct tm *tp, tm;
	char *fmt;

	(void) time(&now);
	tp = localtime(&now);
	(void) memcpy(&tm, tp, sizeof (struct tm));
	fmt = nl_langinfo(_DATE_FMT);

	(void) strftime(time_buf, _SZ_TIME_BUF, fmt, &tm);

	return (time_buf);
}
/*
 * debugging routines
 */


#ifdef DEBUG
static void
print_cache_entry(tnrh_tlb_t *tlbt)
{
	struct in_addr addr;

	addr.s_addr = tlbt->addr;
	(void) fprintf(logf, "\tIP address: %s", inet_ntoa(addr));
	(void) fprintf(logf, "\tTemplate name: %s", tlbt->template_name);
	(void) fprintf(logf, "\tMask length used: %d\n", tlbt->masklen_used);
}

static void
print_cache_entry_v6(tnrh_tlb_ipv6_t *tlbt)
{
	char abuf[INET6_ADDRSTRLEN];

	(void) fprintf(logf, "\tIP address: %s",
	    inet_ntop(AF_INET6, &tlbt->addr, abuf, sizeof (abuf)));
	(void) fprintf(logf, "\tTemplate name: %s", tlbt->template_name);
	(void) fprintf(logf, "\tMask length used: %d\n", tlbt->masklen_used);
}

static void
cachetable_print()
{
	int i;
	tnrh_tlb_t *tlbt;

	(void) fprintf(logf, "-------------------------\n");
	(void) fprintf(logf, "Cache table begin\n");

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++) {
		if ((tlbt = tnrh_cache_table[i]) != NULL)
			print_cache_entry(tlbt);
	}

	(void) fprintf(logf, "Cache table end \n");
	(void) fprintf(logf, "-------------------------\n\n");
}

static void
cachetable_print_v6()
{
	int i;
	tnrh_tlb_ipv6_t *tlbt;

	(void) fprintf(logf, "-------------------------\n");
	(void) fprintf(logf, "Cache table begin\n");

	for (i = 0; i < TNRH_TABLE_HASH_SIZE; i++) {
		if ((tlbt = tnrh_cache_table_v6[i]) != NULL)
			print_cache_entry_v6(tlbt);
	}

	(void) fprintf(logf, "Cache table end \n");
	(void) fprintf(logf, "-------------------------\n\n");
}


static void
print_entry(tsol_rhent_t *ent, int af)
{
	struct sockaddr_in *saddrp;
	struct sockaddr_in6 *saddrp6;
	char abuf[INET6_ADDRSTRLEN];

	if (af == AF_INET) {
		saddrp = (struct sockaddr_in *)&ent->rh_address.ip_addr_v4;
		(void) fprintf(logf, gettext("\tIP address: %s"),
		    inet_ntoa(saddrp->sin_addr));
	} else if (af == AF_INET6) {
		saddrp6 = (struct sockaddr_in6 *)&ent->rh_address.ip_addr_v6;
		(void) fprintf(logf, gettext("\tIP address: %s"),
		    inet_ntop(AF_INET6, &saddrp6->sin6_addr, abuf,
		    sizeof (abuf)));
	}

	(void) fprintf(logf,
	    gettext("\tTemplate name: %s"), ent->rh_template);
	(void) fprintf(logf, gettext("\tprefix_len: %d\n"), ent->rh_prefix);
	(void) fflush(logf);
}

static void
print_tlbt(tnrh_tlb_t *tlbt)
{
	(void) fprintf(logf, "tlbt addr = 0x%4x name = %s \
	    mask = %u, reload = %d\n", tlbt->addr, tlbt->template_name,
	    tlbt->masklen_used, tlbt->reload);
}

static void
rhtable_print()
{
	rhtable_walk(print_entry);
	(void) fprintf(logf, "-----------------------------\n\n");
}

static void
rhtable_print_v6()
{
	rhtable_walk_v6(print_entry);
	(void) fprintf(logf, "-----------------------------\n\n");
}

/*
 * Walk through all the entries in tnrh_entire_table[][]
 * and execute the function passing the entry as argument.
 */
static void
rhtable_walk(void (*action)())
{
	int i, j;
	tnd_tnrhdb_t *rhent;

	for (i = 0; i <= IP_ABITS; i++) {
		if (tnrh_entire_table[i] == NULL)
			continue;

		for (j = 0; j < TNRH_TABLE_HASH_SIZE; j++) {
			rhent = tnrh_entire_table[i][j];

			while (rhent != NULL) {
				action(&rhent->rh_ent, AF_INET);
				rhent = rhent->rh_next;
			}
		}
	}
}

/*
 * Walk through all the entries in tnrh_entire_table_v6[][]
 * and execute the function passing the entry as argument.
 */
static void
rhtable_walk_v6(void (*action)())
{
	int i, j;
	tnd_tnrhdb_t *rhent;

	for (i = 0; i <= IPV6_ABITS; i++) {
		if (tnrh_entire_table_v6[i] == NULL)
			continue;

		for (j = 0; j < TNRH_TABLE_HASH_SIZE; j++) {
			rhent = tnrh_entire_table_v6[i][j];

			while (rhent != NULL) {
				action(&rhent->rh_ent, AF_INET6);
				rhent = rhent->rh_next;
			}
		}
	}
}
#endif /* DEBUG */