summaryrefslogtreecommitdiff
path: root/usr/src/cmd/cmd-inet/usr.sbin/traceroute/traceroute.c
blob: 1b9e1955b92401e2bed73121f14cd0c642c26642 (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
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
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 * Copyright (c) 2017, Joyent, Inc.
 */

/*
 * Copyright (c) 1988, 1989, 1991, 1994, 1995, 1996, 1997
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that: (1) source code distributions
 * retain the above copyright notice and this paragraph in its entirety, (2)
 * distributions including binary code include the above copyright notice and
 * this paragraph in its entirety in the documentation or other materials
 * provided with the distribution, and (3) all advertising materials mentioning
 * features or use of this software display the following acknowledgement:
 * ``This product includes software developed by the University of California,
 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
 * the University nor the names of its contributors may be used to endorse
 * or promote products derived from this software without specific prior
 * written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 *
 * @(#)$Header: traceroute.c,v 1.49 97/06/13 02:30:23 leres Exp $ (LBL)
 */

#include <sys/param.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/sysmacros.h>

#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/ip_icmp.h>
#include <netinet/udp.h>
#include <netinet/udp_var.h>
#include <netinet/ip6.h>
#include <netinet/icmp6.h>

#include <arpa/inet.h>

#include <ctype.h>
#include <errno.h>
#include <malloc.h>
#include <memory.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <libintl.h>
#include <locale.h>
#include <signal.h>
#include <setjmp.h>
#include <limits.h>
#include <zone.h>
#include <thread.h>
#include <synch.h>

#include <priv_utils.h>

#include <libinetutil.h>
#include "traceroute.h"

#define	MAX_SEQ			65535	/* max sequence value for ICMP */
#define	MAX_TRAFFIC_CLASS	255	/* max traffic class for IPv6 */
#define	MAX_FLOW_LABEL		0xFFFFF	/* max flow label for IPv6 */
#define	MAX_TOS			255	/* max type-of-service for IPv4 */
#define	STR_LEN			30

/* store the information about a host */
struct hostinfo {
	char *name;		/* hostname */
	int family;		/* address family of the IP addresses */
	int num_addr;			/* number of IP addresses */
	union any_in_addr *addrs;	/* list of IP addresses */
};

/* used to store a bunch of protocol specific values */
struct pr_set {
	int family;		/* AF_INET or AF_INET6 */
	char name[STR_LEN];	/* "IPv4" or "IPv6" */
	char icmp[STR_LEN];	/* "icmp" or "ipv6-icmp" */
	int icmp_minlen;
	int addr_len;
	int ip_hdr_len;
	int packlen;
	int sock_size;		/* size of sockaddr_in or sockaddr_in6 */
	struct sockaddr *to;
	struct sockaddr *from;
	void *from_sin_addr;
	union any_in_addr *gwIPlist;
	/* pointers to v4/v6 functions */
	struct ip *(*set_buffers_fn) (int);
	int (*check_reply_fn)(struct msghdr *, int, int, uchar_t *, uchar_t *);
	boolean_t (*print_icmp_other_fn)(uchar_t, uchar_t);
	void (*print_addr_fn)(uchar_t *, int, struct sockaddr *);

};

/*
 * LBNL bug fixed: in LBNL traceroute 'uchar_t packet[512];'
 * Not sufficient to hold the complete packet for ECHO REPLY of a big probe.
 * Packet size is reported incorrectly in such a case.
 * Also this buffer needs to be 32 bit aligned. In the future the alignment
 * requirement will be increased to 64 bit. So, let's use 64 bit alignment now.
 */
static uint64_t packet[(IP_MAXPACKET + 1)/8];	/* received packet */

static struct ip *outip4;	/* output buffer to send as an IPv4 datagram */
static struct ip *outip6;	/* output buffer to send as an IPv6 datagram */

/* Used to store the ancillary data that comes with the received packets */
static uint64_t ancillary_data[(IP_MAXPACKET + 1)/8];

/* first get the gw names, later you'll resolve them based on the family */
static char *gwlist[MAXMAX_GWS];		/* gateway names list */
static union any_in_addr gwIPlist[MAX_GWS];	/* gateway IPv4 address list */
static union any_in_addr gwIP6list[MAX_GWS6];	/* gateway IPv6 address list */

static int family_input = AF_UNSPEC;	/* User supplied protocol family */
static int rcvsock4;		/* receive (icmp) socket file descriptor */
static int sndsock4;		/* send (udp/icmp) socket file descriptor */
static int rcvsock6;		/* receive (icmp6) socket file descriptor */
static int sndsock6;		/* send (udp6/icmp6) socket file descriptor */
int gw_count = 0;		/* number of gateways */
static struct sockaddr_in whereto;	/* Who to try to reach */
static struct sockaddr_in6 whereto6;
static struct sockaddr_in wherefrom;	/* Who we are */
static struct sockaddr_in6 wherefrom6;
static int packlen_input = 0;		/* user input for packlen */

char *prog;
static char *source_input = NULL; /* this is user arg. source, doesn't change */
static char *source = NULL;	/* this gets modified after name lookup */
char *hostname;
static char *device = NULL;   	/* interface name */
static struct pr_set *pr4;	/* protocol info for IPv4 */
static struct pr_set *pr6;	/* protocol info for IPv6 */
static struct ifaddrlist *al4;	/* list of interfaces */
static struct ifaddrlist *al6;	/* list of interfaces */
static uint_t if_index = 0;	/* interface index */
static int num_v4 = 0;		/* count of IPv4 addresses */
static int num_v6 = 0;		/* count of IPv6 addresses */
static int num_ifs4 = 0;	/* count of local IPv4 interfaces */
static int num_ifs6 = 0;	/* count of local IPv6 interfaces */

static int nprobes = 3;		/* number of probes */
static int max_ttl = 30;	/* max number of hops */
static int first_ttl = 1;	/* initial number of hops */
ushort_t ident;			/* used to authenticate replies */
ushort_t port = 32768 + 666;	/* start udp dest port # for probe packets */

static int options = 0;		/* socket options */
boolean_t verbose = _B_FALSE;	/* verbose output */
static int waittime = 5;	/* time to wait for response (in seconds) */
static struct timeval delay = {0, 0}; /* delay between consecutive probe */
boolean_t nflag = _B_FALSE;	/* print addresses numerically */
static boolean_t showttl = _B_FALSE; /* print the ttl(hop limit) of recvd pkt */
boolean_t useicmp = _B_FALSE;  	/* use icmp echo instead of udp packets */
boolean_t docksum = _B_TRUE;	/* calculate checksums */
static boolean_t collect_stat = _B_FALSE;	/* print statistics */
boolean_t settos = _B_FALSE;   	/* set type-of-service field */
int dontfrag = 0;		/* IP*_DONTFRAG */
static int max_timeout = 5;	/* quit after this consecutive timeouts */
static boolean_t probe_all = _B_FALSE;	/* probe all the IFs of the target */
static boolean_t pick_src = _B_FALSE;	/* traceroute picks the src address */

/*
 * flow and class are specific to IPv6, tos and off are specific to IPv4.
 * Each protocol uses the ones that are specific to itself, and ignores
 * others.
 */
static uint_t flow = 0;		/* IPv6 flow info */
static uint_t class = 0;	/* IPv6 class */
uchar_t tos = 0;		/* IPv4 type-of-service */
ushort_t off = 0;		/* set DF bit */

static jmp_buf env;		/* stack environment for longjmp() */
boolean_t raw_req;		/* if sndsock for IPv4 must be raw */

/*
 * Name service lookup related data.
 */
static mutex_t tr_nslock = ERRORCHECKMUTEX;
static boolean_t tr_nsactive = _B_FALSE;	/* Lookup ongoing */
static hrtime_t tr_nsstarttime;			/* Start time */
static int tr_nssleeptime = 2;			/* Interval between checks */
static int tr_nswarntime = 2;			/* Interval to warn after */

/* Forwards */
static uint_t calc_packetlen(int, struct pr_set *);
extern int check_reply(struct msghdr *, int, int, uchar_t *, uchar_t *);
extern int check_reply6(struct msghdr *, int, int, uchar_t *, uchar_t *);
static double deltaT(struct timeval *, struct timeval *);
static char *device_name(struct ifaddrlist *, int, union any_in_addr *,
    struct pr_set *);
extern void *find_ancillary_data(struct msghdr *, int, int);
static boolean_t has_addr(struct addrinfo *, union any_in_addr *);
static struct ifaddrlist *find_device(struct ifaddrlist *, int, char *);
static struct ifaddrlist *find_ifaddr(struct ifaddrlist *, int,
    union any_in_addr *, int);
static void get_gwaddrs(char **, int, union any_in_addr *,
    union any_in_addr *, int *, int *);
static void get_hostinfo(char *, int, struct addrinfo **);
char *inet_name(union any_in_addr *, int);
ushort_t in_cksum(ushort_t *, int);
extern int ip_hdr_length_v6(ip6_t *, int, uint8_t *);
extern char *pr_type(uchar_t);
extern char *pr_type6(uchar_t);
extern void print_addr(uchar_t *, int, struct sockaddr *);
extern void print_addr6(uchar_t *, int, struct sockaddr *);
extern boolean_t print_icmp_other(uchar_t, uchar_t);
extern boolean_t print_icmp_other6(uchar_t, uchar_t);
static void print_stats(int, int, double, double, double, double);
static void print_unknown_host_msg(const char *, const char *);
static void record_stats(double, int *, double *, double *, double *, double *);
static void resolve_nodes(int *, struct addrinfo **);
static void select_src_addr(union any_in_addr *, union any_in_addr *, int);
extern void send_probe(int, struct sockaddr *, struct ip *, int, int,
    struct timeval *, int);
extern void send_probe6(int, struct msghdr *, struct ip *, int, int,
    struct timeval *, int);
extern void set_ancillary_data(struct msghdr *, int, union any_in_addr *, int,
    uint_t);
extern struct ip *set_buffers(int);
extern struct ip *set_buffers6(int);
extern void set_IPv4opt_sourcerouting(int, union any_in_addr *,
    union any_in_addr *);
static void set_sin(struct sockaddr *, union any_in_addr *, int);
static int set_src_addr(struct pr_set *, struct ifaddrlist **);
static void setup_protocol(struct pr_set *, int);
static void setup_socket(struct pr_set *, int);
static void sig_handler(int);
static int str2int(const char *, const char *, int, int);
static double str2dbl(const char *, const char *, double, double);
static void trace_it(struct addrinfo *);
static void traceroute(union any_in_addr *, struct msghdr *, struct pr_set *,
    int, struct ifaddrlist *);
static void tv_sub(struct timeval *, struct timeval *);
static void usage(void);
static int wait_for_reply(int, struct msghdr *, struct timeval *);
static double xsqrt(double);
static void *ns_warning_thr(void *);

/*
 * main
 */
int
main(int argc, char **argv)
{
	struct addrinfo *ai_dst = NULL;		/* destination host */
	/*
	 * "probing_successful" indicates if we could successfully send probes,
	 * not necessarily received reply from the target (this behavior is from
	 * the original traceroute). It's _B_FALSE if packlen is invalid, or no
	 * interfaces found.
	 */
	boolean_t probing_successful = _B_FALSE;
	int longjmp_return;			/* return value from longjump */
	int i = 0;
	char *cp;
	int op;
	char *ep;
	char temp_buf[INET6_ADDRSTRLEN];	/* use for inet_ntop() */
	double pause;

	/*
	 * A raw socket will be used for IPv4 if there is sufficient
	 * privilege.
	 */
	raw_req = priv_ineffect(PRIV_NET_RAWACCESS);

	/*
	 * We'll need the privilege only when we open the sockets; that's
	 * when we'll fail if the program has insufficient privileges.
	 */
	(void) __init_suid_priv(PU_CLEARLIMITSET, PRIV_NET_ICMPACCESS,
	    raw_req ? PRIV_NET_RAWACCESS : NULL, NULL);

	(void) setlinebuf(stdout);

	if ((cp = strrchr(argv[0], '/')) != NULL)
		prog = cp + 1;
	else
		prog = argv[0];

	opterr = 0;
	while ((op = getopt(argc, argv, "adFIlnrSvxA:c:f:g:i:L:m:P:p:Q:q:s:"
	    "t:w:")) != EOF) {
		switch (op) {
		case 'A':
			if (strcmp(optarg, "inet") == 0) {
				family_input = AF_INET;
			} else if (strcmp(optarg, "inet6") == 0) {
				family_input = AF_INET6;
			} else {
				Fprintf(stderr,
				    "%s: unknown address family %s\n",
				    prog, optarg);
				exit(EXIT_FAILURE);
			}
			break;

		case 'a':
			probe_all = _B_TRUE;
			break;

		case 'c':
			class = str2int(optarg, "traffic class", 0,
			    MAX_TRAFFIC_CLASS);
			break;

		case 'd':
			options |= SO_DEBUG;
			break;

		case 'f':
			first_ttl = str2int(optarg, "first ttl", 1, MAXTTL);
			break;

		case 'F':
			off = IP_DF;
			dontfrag = 1;
			break;

		case 'g':
			if (!raw_req) {
				Fprintf(stderr,
				    "%s: privilege to specify a loose source "
				    "route gateway is unavailable\n",
				    prog);
				exit(EXIT_FAILURE);
			}
			if (gw_count >= MAXMAX_GWS) {
				Fprintf(stderr,
				    "%s: Too many gateways\n", prog);
				exit(EXIT_FAILURE);
			}
			gwlist[gw_count] = strdup(optarg);
			if (gwlist[gw_count] == NULL) {
				Fprintf(stderr, "%s: strdup %s\n", prog,
				    strerror(errno));
				exit(EXIT_FAILURE);
			}

			++gw_count;
			break;

		case 'l':
			showttl = _B_TRUE;
			break;

		case 'i':
			/* this can be IF name or IF index */
			if_index = (uint_t)strtol(optarg, &ep, 10);

			/* convert IF index <-->  IF name */
			if (errno != 0 || *ep != '\0') {
				device = optarg;
				if_index = if_nametoindex((const char *)device);

				/*
				 * In case it fails, check to see if the problem
				 * is other than "IF not found".
				 */
				if (if_index == 0 && errno != ENXIO) {
					Fprintf(stderr, "%s: if_nametoindex:"
					    "%s\n", prog, strerror(errno));
					exit(EXIT_FAILURE);
				}
			} else {
				device = (char *)malloc(LIFNAMSIZ + 1);
				if (device == NULL) {
					Fprintf(stderr, "%s: malloc: %s\n",
					    prog, strerror(errno));
					exit(EXIT_FAILURE);
				}

				device = if_indextoname(if_index, device);
				if (device != NULL) {
					device[LIFNAMSIZ] = '\0';
				} else if (errno != ENXIO) {
					/*
					 * The problem was other than "index
					 * not found".
					 */
					Fprintf(stderr, "%s: if_indextoname:"
					    "%s\n", prog, strerror(errno));
					exit(EXIT_FAILURE);
				}
			}

			if (device == NULL || if_index == 0) {
				Fprintf(stderr, "%s: interface %s "
				    "doesn't match any actual interfaces\n",
				    prog, optarg);
				exit(EXIT_FAILURE);
			}
			break;

		case 'I':
			useicmp = _B_TRUE;
			break;

		case 'L':
			flow = str2int(optarg, "flow label", 0, MAX_FLOW_LABEL);
			break;

		case 'm':
			max_ttl = str2int(optarg, "max ttl(hop limit)", 1,
			    MAXTTL);
			break;

		case 'n':
			nflag = _B_TRUE;
			break;

		case 'P':
			pause = str2dbl(optarg, "pause", 0, INT_MAX);
			delay.tv_sec = (time_t)pause;
			delay.tv_usec = (suseconds_t)((pause - delay.tv_sec) *
			    1000000);
			break;

		case 'p':
			port = str2int(optarg, "port", 1, MAX_PORT);
			break;

		case 'Q':
			max_timeout = str2int(optarg, "max timeout", 1, -1);
			break;

		case 'q':
			nprobes = str2int(optarg, "nprobes", 1, -1);
			break;

		case 'r':
			options |= SO_DONTROUTE;
			break;

		case 'S':
			collect_stat = _B_TRUE;
			break;

		case 's':
			/*
			 * set the ip source address of the outbound
			 * probe (e.g., on a multi-homed host).
			 */
			source_input = optarg;
			break;

		case 't':
			tos = (uchar_t)str2int(optarg, "tos", 0, MAX_TOS);
			settos = _B_TRUE;
			break;

		case 'v':
			verbose = _B_TRUE;
			break;

		case 'x':
			docksum = _B_FALSE;
			break;

		case 'w':
			waittime = str2int(optarg, "wait time", 2, -1);
			break;

		default:
			usage();
			break;
		}
	}

	/*
	 * If it's probe_all, SIGQUIT makes traceroute exit(). But we set the
	 * address to jump back to in traceroute(). Until then, we'll need to
	 * temporarily specify one.
	 */
	if (probe_all) {
		if ((longjmp_return = setjmp(env)) != 0) {
			if (longjmp_return == SIGQUIT) {
				Printf("(exiting)\n");
				exit(EXIT_SUCCESS);
			} else {		/* should never happen */
				exit(EXIT_FAILURE);
			}
		}
		(void) signal(SIGQUIT, sig_handler);
	}

	if ((gw_count > 0) && (options & SO_DONTROUTE)) {
		Fprintf(stderr, "%s: loose source route gateways (-g)"
		    " cannot be specified when probe packets are sent"
		    " directly to a host on an attached network (-r)\n",
		    prog);
		exit(EXIT_FAILURE);
	}

	i = argc - optind;
	if (i == 1 || i == 2) {
		hostname = argv[optind];

		if (i == 2) {
			/* accept any length now, we'll check it later */
			packlen_input = str2int(argv[optind + 1],
			    "packet length", 0, -1);
		}
	} else {
		usage();
	}

	if (first_ttl > max_ttl) {
		Fprintf(stderr,
		    "%s: first ttl(hop limit) (%d) may not be greater"
		    " than max ttl(hop limit) (%d)\n",
		    prog, first_ttl, max_ttl);
		exit(EXIT_FAILURE);
	}

	/*
	 * Start up the name services warning thread.
	 */
	if (thr_create(NULL, 0, ns_warning_thr, NULL,
	    THR_DETACHED | THR_DAEMON, NULL) != 0) {
		Fprintf(stderr, "%s: failed to create name services "
		    "thread: %s\n", prog, strerror(errno));
		exit(EXIT_FAILURE);
	}


	/* resolve hostnames */
	resolve_nodes(&family_input, &ai_dst);
	if (ai_dst == NULL) {
		exit(EXIT_FAILURE);
	}

	/*
	 * If it's probe_all, SIGINT makes traceroute skip to probing next IP
	 * address of the target. The new interrupt handler is assigned in
	 * traceroute() function. Until then let's ignore the signal.
	 */
	if (probe_all)
		(void) signal(SIGINT, SIG_IGN);

	ident = (getpid() & 0xffff) | 0x8000;

	/*
	 * We KNOW that probe_all == TRUE if family is AF_UNSPEC,
	 * since family is set to the specific AF found unless it's
	 * probe_all. So if family == AF_UNSPEC, we need to init pr4 and pr6.
	 */
	switch (family_input) {
	case AF_UNSPEC:
		pr4 = (struct pr_set *)malloc(sizeof (struct pr_set));
		if (pr4 == NULL) {
			Fprintf(stderr,
			    "%s: malloc %s\n", prog, strerror(errno));
			exit(EXIT_FAILURE);
		}
		pr6 = (struct pr_set *)malloc(sizeof (struct pr_set));
		if (pr6 == NULL) {
			Fprintf(stderr,
			    "%s: malloc %s\n", prog, strerror(errno));
			exit(EXIT_FAILURE);
		}
		setup_protocol(pr6, AF_INET6);
		setup_protocol(pr4, AF_INET);
		outip6 = (*pr6->set_buffers_fn)(pr6->packlen);
		setup_socket(pr6, pr6->packlen);

		outip4 = (*pr4->set_buffers_fn)(pr4->packlen);
		setup_socket(pr4, pr4->packlen);
		num_ifs6 = set_src_addr(pr6, &al6);
		num_ifs4 = set_src_addr(pr4, &al4);
		break;
	case AF_INET6:
		pr6 = (struct pr_set *)malloc(sizeof (struct pr_set));
		if (pr6 == NULL) {
			Fprintf(stderr,
			    "%s: malloc %s\n", prog, strerror(errno));
			exit(EXIT_FAILURE);
		}
		setup_protocol(pr6, AF_INET6);
		outip6 = (*pr6->set_buffers_fn)(pr6->packlen);
		setup_socket(pr6, pr6->packlen);
		num_ifs6 = set_src_addr(pr6, &al6);
		break;
	case AF_INET:
		pr4 = (struct pr_set *)malloc(sizeof (struct pr_set));
		if (pr4 == NULL) {
			Fprintf(stderr,
			    "%s: malloc %s\n", prog, strerror(errno));
			exit(EXIT_FAILURE);
		}
		setup_protocol(pr4, AF_INET);
		outip4 = (*pr4->set_buffers_fn)(pr4->packlen);
		setup_socket(pr4, pr4->packlen);
		num_ifs4 = set_src_addr(pr4, &al4);
		break;
	default:
		Fprintf(stderr, "%s: unknow address family.\n", prog);
		exit(EXIT_FAILURE);
	}

	if (num_v4 + num_v6 > 1 && !probe_all) {
		if (ai_dst->ai_family == AF_INET) {
			Fprintf(stderr,
			    "%s: Warning: %s has multiple addresses;"
			    " using %s\n", prog, hostname,
			    inet_ntop(AF_INET,
			    /* LINTED E_BAD_PTR_CAST_ALIGN */
			    (void *)&((struct sockaddr_in *)
			    ai_dst->ai_addr)->sin_addr,
			    temp_buf, sizeof (temp_buf)));
		} else {
			Fprintf(stderr,
			    "%s: Warning: %s has multiple addresses;"
			    " using %s\n", prog, hostname,
			    inet_ntop(AF_INET6,
			    /* LINTED E_BAD_PTR_CAST_ALIGN */
			    (void *)&((struct sockaddr_in6 *)
			    ai_dst->ai_addr)->sin6_addr,
			    temp_buf, sizeof (temp_buf)));
		}
	}

	if (num_ifs4 + num_ifs6 > 0) {
		trace_it(ai_dst);
		probing_successful = _B_TRUE;
	}

	(void) close(rcvsock4);
	(void) close(sndsock4);
	(void) close(rcvsock6);
	(void) close(sndsock6);

	/*
	 * if we could probe any of the IP addresses of the target, that means
	 * this was a successful operation
	 */
	if (probing_successful)
		return (EXIT_SUCCESS);
	else
		return (EXIT_FAILURE);
}

/*
 * print "unknown host" message
 */
static void
print_unknown_host_msg(const char *protocol, const char *host)
{
	Fprintf(stderr, "%s: unknown%s host %s\n", prog, protocol, host);
}

/*
 * resolve destination host and gateways
 */
static void
resolve_nodes(int *family, struct addrinfo **ai_dstp)
{
	struct addrinfo *ai_dst = NULL;
	struct addrinfo *aip = NULL;
	int num_resolved_gw = 0;
	int num_resolved_gw6 = 0;

	get_hostinfo(hostname, *family, &ai_dst);
	if (ai_dst == NULL) {
		print_unknown_host_msg("", hostname);
		exit(EXIT_FAILURE);
	}
	/* Get a count of the v4 & v6 addresses */
	for (aip = ai_dst; aip != NULL; aip = aip->ai_next) {
		switch (aip->ai_family) {
		case AF_INET:
			num_v4++;
			break;
		case AF_INET6:
			num_v6++;
			break;
		}
	}

	if (*family == AF_UNSPEC && !probe_all) {
		*family = ai_dst->ai_family;
	}

	/* resolve gateways */
	if (gw_count > 0) {
		get_gwaddrs(gwlist, *family, gwIPlist, gwIP6list,
		    &num_resolved_gw, &num_resolved_gw6);

		/* we couldn't resolve a gateway as an IPv6 host */
		if (num_resolved_gw6 != gw_count && num_v6 != 0) {
			if (*family == AF_INET6 || *family == AF_UNSPEC)
				print_unknown_host_msg(" IPv6",
				    gwlist[num_resolved_gw6]);
			num_v6 = 0;
		}

		/* we couldn't resolve a gateway as an IPv4 host */
		if (num_resolved_gw != gw_count && num_v4 != 0) {
			if (*family == AF_INET || *family == AF_UNSPEC)
				print_unknown_host_msg(" IPv4",
				    gwlist[num_resolved_gw]);
			num_v4 = 0;
		}
	}

	*ai_dstp = (num_v4 + num_v6 > 0) ? ai_dst : NULL;
}

/*
 * Given IP address or hostname, return v4 and v6 hostinfo lists.
 * Assumes that hostinfo ** ptrs are non-null.
 */
static void
get_hostinfo(char *host, int family, struct addrinfo **aipp)
{
	struct addrinfo hints, *ai;
	struct in6_addr addr6;
	struct in_addr addr;
	char abuf[INET6_ADDRSTRLEN];	/* use for inet_ntop() */
	int rc;

	/*
	 * Take care of v4-mapped addresses. It should run same as v4, after
	 * chopping off the prefix, leaving the IPv4 address
	 */
	if ((inet_pton(AF_INET6, host, &addr6) > 0) &&
	    IN6_IS_ADDR_V4MAPPED(&addr6)) {
		/* peel off the "mapping" stuff, leaving 32 bit IPv4 address */
		IN6_V4MAPPED_TO_INADDR(&addr6, &addr);

		/* convert it back to a string */
		(void) inet_ntop(AF_INET, &addr, abuf, sizeof (abuf));

		/* now the host is an IPv4 address */
		(void) strcpy(host, abuf);

		/*
		 * If it's a mapped address, we convert it into IPv4
		 * address because traceroute will send and receive IPv4
		 * packets for that address. Therefore, it's a failure case to
		 * ask get_hostinfo() to treat a mapped address as an IPv6
		 * address.
		 */
		if (family == AF_INET6) {
			return;
		}
	}

	(void) memset(&hints, 0, sizeof (hints));
	hints.ai_family = family;
	hints.ai_flags = AI_ADDRCONFIG | AI_CANONNAME;
	rc = getaddrinfo(host, NULL, &hints, &ai);
	if (rc != 0) {
		if (rc != EAI_NONAME)
			Fprintf(stderr, "%s: getaddrinfo: %s\n", prog,
			    gai_strerror(rc));
		*aipp = NULL;
		return;
	}
	*aipp = ai;
}

/*
 * Calculate the packet length to be used, and check against the valid range.
 * Returns -1 if range check fails.
 */
static uint_t
calc_packetlen(int plen_input, struct pr_set *pr)
{
	int minpacket;			/* min ip packet size */
	int optlen;			/* length of ip options */
	int plen;

	/*
	 * LBNL bug fixed: miscalculation of optlen
	 */
	if (gw_count > 0) {
		/*
		 * IPv4:
		 * ----
		 * 5 (NO OPs) + 3 (code, len, ptr) + gateways
		 * IP options field can hold up to 9 gateways. But the API
		 * allows you to specify only 8, because the last one is the
		 * destination host. When this packet is sent, on the wire
		 * you see one gateway replaced by 4 NO OPs. The other 1 NO
		 * OP is for alignment
		 *
		 * IPv6:
		 * ----
		 * Well, formula is different, but the result is same.
		 * 8 byte fixed part for Type 0 Routing header, followed by
		 * gateway addresses
		 */
		optlen = 8 + gw_count * pr->addr_len;
	} else {
		optlen = 0;
	}

	/* take care of the packet length calculations and checks */
	minpacket = pr->ip_hdr_len + sizeof (struct outdata) + optlen;
	if (useicmp)
		minpacket += pr->icmp_minlen;	/* minimum ICMP header size */
	else
		minpacket += sizeof (struct udphdr);
	plen = plen_input;
	if (plen == 0) {
		plen = minpacket;		/* minimum sized packet */
	} else if (minpacket > plen || plen > IP_MAXPACKET) {
		Fprintf(stderr, "%s: %s packet size must be >= %d and <= %d\n",
		    prog, pr->name, minpacket, IP_MAXPACKET);
		return (0);
	}

	return (plen);
}

/*
 * Sets the source address by resolving -i and -s arguments, or if -i and -s
 * don't dictate any, it sets the pick_src to make sure traceroute uses the
 * kernel's pick of the source address.
 * Returns number of interfaces configured on the source host, 0 on error or
 * there's no interface which is up amd not a loopback.
 */
static int
set_src_addr(struct pr_set *pr, struct ifaddrlist **alp)
{
	union any_in_addr *ap;
	struct ifaddrlist *al = NULL;
	struct ifaddrlist *tmp1_al = NULL;
	struct ifaddrlist *tmp2_al = NULL;
	/* LINTED E_BAD_PTR_CAST_ALIGN */
	struct sockaddr_in *sin_from = (struct sockaddr_in *)pr->from;
	/* LINTED E_BAD_PTR_CAST_ALIGN */
	struct sockaddr_in6 *sin6_from = (struct sockaddr_in6 *)pr->from;
	struct addrinfo *aip;
	char errbuf[ERRBUFSIZE];
	char abuf[INET6_ADDRSTRLEN];		/* use for inet_ntop() */
	int num_ifs;				/* all the interfaces  */
	int num_src_ifs;			/* exclude loopback and down */
	int i;
	uint_t ifaddrflags = 0;

	source = source_input;

	if (device != NULL)
		ifaddrflags |= LIFC_UNDER_IPMP;

	/* get the interface address list */
	num_ifs = ifaddrlist(&al, pr->family, ifaddrflags, errbuf);
	if (num_ifs < 0) {
		Fprintf(stderr, "%s: ifaddrlist: %s\n", prog, errbuf);
		exit(EXIT_FAILURE);
	}

	num_src_ifs = 0;
	for (i = 0; i < num_ifs; i++) {
		if (!(al[i].flags & IFF_LOOPBACK) && (al[i].flags & IFF_UP))
			num_src_ifs++;
	}

	if (num_src_ifs == 0) {
		Fprintf(stderr, "%s: can't find any %s network interfaces\n",
		    prog, pr->name);
		return (0);
	}

	/* verify the device */
	if (device != NULL) {
		tmp1_al = find_device(al, num_ifs, device);

		if (tmp1_al == NULL) {
			Fprintf(stderr, "%s: %s (index %d) is an invalid %s"
			    " interface\n", prog, device, if_index, pr->name);
			free(al);
			return (0);
		}
	}

	/* verify the source address */
	if (source != NULL) {
		get_hostinfo(source, pr->family, &aip);
		if (aip == NULL) {
			Fprintf(stderr,
			    "%s: %s is an invalid %s source address\n",
			    prog, source, pr->name);

			free(al);
			return (0);
		}

		source = aip->ai_canonname;

		if (pr->family == AF_INET)
			ap = (union any_in_addr *)
			    /* LINTED E_BAD_PTR_CAST_ALIGN */
			    &((struct sockaddr_in *)aip->ai_addr)->sin_addr;
		else
			ap = (union any_in_addr *)
			    /* LINTED E_BAD_PTR_CAST_ALIGN */
			    &((struct sockaddr_in6 *)aip->ai_addr)->sin6_addr;

		/*
		 * LBNL bug fixed: used to accept any src address
		 */
		tmp2_al = find_ifaddr(al, num_ifs, ap, pr->family);
		if (tmp2_al == NULL) {
			(void) inet_ntop(pr->family, ap, abuf, sizeof (abuf));
			Fprintf(stderr, "%s: %s is not a local %s address\n",
			    prog, abuf, pr->name);
			free(al);
			freeaddrinfo(aip);
			return (0);
		}
	}

	pick_src = _B_FALSE;

	if (source == NULL) {			/* no -s used */
		if (device == NULL) {		/* no -i used, no -s used */
			pick_src = _B_TRUE;
		} else {			/* -i used, no -s used */
			/*
			 * -i used, but not -s, and it's IPv4: set the source
			 * address to whatever the interface has configured on
			 * it.
			 */
			if (pr->family == AF_INET)
				set_sin(pr->from, &(tmp1_al->addr), pr->family);
			else
				pick_src = _B_TRUE;
		}
	} else {				/* -s used */
		if (device == NULL) {		/* no -i used, -s used */
			set_sin(pr->from, ap, pr->family);

			if (aip->ai_next != NULL) {
				(void) inet_ntop(pr->family, pr->from_sin_addr,
				    abuf, sizeof (abuf));
				Fprintf(stderr, "%s: Warning: %s has multiple "
				    "addresses; using %s\n", prog, source,
				    abuf);
			}
		} else {			/* -i and -s used */
			/*
			 * Make sure the source specified matches the
			 * interface address. You only care about this for IPv4
			 * IPv6 can handle IF not matching src address
			 */
			if (pr->family == AF_INET) {
				if (!has_addr(aip, &tmp1_al->addr)) {
					Fprintf(stderr,
					    "%s: %s is not on interface %s\n",
					    prog, source, device);
					exit(EXIT_FAILURE);
				}
				/*
				 * make sure we use the one matching the
				 * interface's address
				 */
				*ap = tmp1_al->addr;
			}

			set_sin(pr->from, ap, pr->family);
		}
	}

	/*
	 * Binding at this point will set the source address to be used
	 * for both IPv4 (when raw IP datagrams are not required) and
	 * IPv6.  If the address being bound to is zero, then the kernel
	 * will end up choosing the source address when the datagram is
	 * sent.
	 *
	 * For raw IPv4 datagrams, the source address is initialized
	 * within traceroute() along with the outbound destination
	 * address.
	 */
	if (pr->family == AF_INET && !raw_req) {
		sin_from->sin_family = AF_INET;
		sin_from->sin_port = htons(ident);
		if (bind(sndsock4, (struct sockaddr *)pr->from,
			sizeof (struct sockaddr_in)) < 0) {
			Fprintf(stderr, "%s: bind: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	} else if (pr->family == AF_INET6) {
		sin6_from->sin6_family = AF_INET6;
		sin6_from->sin6_port = htons(ident);
		if (bind(sndsock6, (struct sockaddr *)pr->from,
			sizeof (struct sockaddr_in6)) < 0) {
			Fprintf(stderr, "%s: bind: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}

		whereto6.sin6_flowinfo = htonl((class << 20) | flow);
	}
	*alp = al;
	return (num_ifs);
}

/*
 * Returns the complete ifaddrlist structure matching the desired interface
 * address. Ignores interfaces which are either down or loopback.
 */
static struct ifaddrlist *
find_ifaddr(struct ifaddrlist *al, int len, union any_in_addr *addr,
    int family)
{
	struct ifaddrlist *tmp_al = al;
	int i;
	size_t addr_len = (family == AF_INET) ? sizeof (struct in_addr) :
	    sizeof (struct in6_addr);

	for (i = 0; i < len; i++, tmp_al++) {
		if ((!(tmp_al->flags & IFF_LOOPBACK) &&
		    (tmp_al->flags & IFF_UP)) &&
		    (memcmp(&tmp_al->addr, addr, addr_len) == 0))
			break;
	}

	if (i < len) {
		return (tmp_al);
	} else {
		return (NULL);
	}
}

/*
 * Returns the complete ifaddrlist structure matching the desired interface name
 * Ignores interfaces which are either down or loopback.
 */
static struct ifaddrlist *
find_device(struct ifaddrlist *al, int len, char *device)
{
	struct ifaddrlist *tmp_al = al;
	int i;

	for (i = 0; i < len; i++, tmp_al++) {
		if ((!(tmp_al->flags & IFF_LOOPBACK) &&
		    (tmp_al->flags & IFF_UP)) &&
		    (strcmp(tmp_al->device, device) == 0))
			break;
	}

	if (i < len) {
		return (tmp_al);
	} else {
		return (NULL);
	}
}

/*
 * returns _B_TRUE if given hostinfo contains the given address
 */
static boolean_t
has_addr(struct addrinfo *ai, union any_in_addr *addr)
{
	struct addrinfo *ai_tmp = NULL;
	union any_in_addr *ap;

	for (ai_tmp = ai; ai_tmp != NULL; ai_tmp = ai_tmp->ai_next) {
		if (ai_tmp->ai_family == AF_INET6)
			continue;
		ap = (union any_in_addr *)
		    /* LINTED E_BAD_PTR_CAST_ALIGN */
		    &((struct sockaddr_in *)ai_tmp->ai_addr)->sin_addr;
		if (memcmp(ap, addr, sizeof (struct in_addr)) == 0)
			break;
	}

	if (ai_tmp != NULL) {
		return (_B_TRUE);
	} else {
		return (_B_FALSE);
	}
}

/*
 * Resolve the gateway names, splitting results into v4 and v6 lists.
 * Gateway addresses are added to the appropriate passed-in array; the
 * number of resolved gateways for each af is returned in resolved[6].
 * Assumes that passed-in arrays are large enough for MAX_GWS[6] addrs
 * and resolved[6] ptrs are non-null; ignores array and counter if the
 * address family param makes them irrelevant.
 */
static void
get_gwaddrs(char **gwlist, int family, union any_in_addr *gwIPlist,
    union any_in_addr *gwIPlist6, int *resolved, int *resolved6)
{
	int i;
	boolean_t check_v4 = _B_TRUE, check_v6 = _B_TRUE;
	struct addrinfo *ai = NULL;
	struct addrinfo *aip = NULL;

	*resolved = *resolved6 = 0;
	switch (family) {
	case AF_UNSPEC:
		break;
	case AF_INET:
		check_v6 = _B_FALSE;
		break;
	case AF_INET6:
		check_v4 = _B_FALSE;
		break;
	default:
		return;
	}

	if (check_v4 && gw_count >= MAX_GWS) {
		check_v4 = _B_FALSE;
		Fprintf(stderr, "%s: too many IPv4 gateways\n", prog);
		num_v4 = 0;
	}
	if (check_v6 && gw_count >= MAX_GWS6) {
		check_v6 = _B_FALSE;
		Fprintf(stderr, "%s: too many IPv6 gateways\n", prog);
		num_v6 = 0;
	}

	for (i = 0; i < gw_count; i++) {
		if (!check_v4 && !check_v6)
			return;
		get_hostinfo(gwlist[i], family, &ai);
		if (ai == NULL)
			return;
		if (check_v4 && num_v4 != 0) {
			check_v4 = _B_FALSE;
			for (aip = ai; aip != NULL; aip = aip->ai_next) {
				if (aip->ai_family == AF_INET) {
					/* LINTED E_BAD_PTR_CAST_ALIGN */
					bcopy(&((struct sockaddr_in *)
					    aip->ai_addr)->sin_addr,
					    &gwIPlist[i].addr,
					    aip->ai_addrlen);
					(*resolved)++;
					check_v4 = _B_TRUE;
					break;
				}
			}
		} else if (check_v4) {
			check_v4 = _B_FALSE;
		}
		if (check_v6 && num_v6 != 0) {
			check_v6 = _B_FALSE;
			for (aip = ai; aip != NULL; aip = aip->ai_next) {
				if (aip->ai_family == AF_INET6) {
					/* LINTED E_BAD_PTR_CAST_ALIGN */
					bcopy(&((struct sockaddr_in6 *)
					    aip->ai_addr)->sin6_addr,
					    &gwIPlist6[i].addr6,
					    aip->ai_addrlen);
					(*resolved6)++;
					check_v6 = _B_TRUE;
					break;
				}
			}
		} else if (check_v6) {
			check_v6 = _B_FALSE;
		}
	}
	freeaddrinfo(ai);
}

/*
 * set protocol specific values here
 */
static void
setup_protocol(struct pr_set *pr, int family)
{
	/*
	 * Set the global variables for each AF. This is going to save us lots
	 * of "if (family == AF_INET)... else .."
	 */
	pr->family = family;

	if (family == AF_INET) {
		if (!docksum) {
			Fprintf(stderr,
			    "%s: Warning: checksums disabled\n", prog);
		}
		(void) strcpy(pr->name, "IPv4");
		(void) strcpy(pr->icmp, "icmp");
		pr->icmp_minlen = ICMP_MINLEN;
		pr->addr_len = sizeof (struct in_addr);
		pr->ip_hdr_len = sizeof (struct ip);
		pr->sock_size = sizeof (struct sockaddr_in);
		pr->to = (struct sockaddr *)&whereto;
		pr->from = (struct sockaddr *)&wherefrom;
		pr->from_sin_addr = (void *)&wherefrom.sin_addr;
		pr->gwIPlist = gwIPlist;
		pr->set_buffers_fn = set_buffers;
		pr->check_reply_fn = check_reply;
		pr->print_icmp_other_fn = print_icmp_other;
		pr->print_addr_fn = print_addr;
		pr->packlen = calc_packetlen(packlen_input, pr);
	} else {
		(void) strcpy(pr->name, "IPv6");
		(void) strcpy(pr->icmp, "ipv6-icmp");
		pr->icmp_minlen = ICMP6_MINLEN;
		pr->addr_len = sizeof (struct in6_addr);
		pr->ip_hdr_len = sizeof (struct ip6_hdr);
		pr->sock_size = sizeof (struct sockaddr_in6);
		pr->to = (struct sockaddr *)&whereto6;
		pr->from = (struct sockaddr *)&wherefrom6;
		pr->from_sin_addr = (void *)&wherefrom6.sin6_addr;
		pr->gwIPlist = gwIP6list;
		pr->set_buffers_fn = set_buffers6;
		pr->check_reply_fn = check_reply6;
		pr->print_icmp_other_fn = print_icmp_other6;
		pr->print_addr_fn = print_addr6;
		pr->packlen = calc_packetlen(packlen_input, pr);
	}
	if (pr->packlen == 0)
		exit(EXIT_FAILURE);
}

/*
 * setup the sockets for the given protocol's address family
 */
static void
setup_socket(struct pr_set *pr, int packet_len)
{
	int on = 1;
	struct protoent *pe;
	int type;
	int proto;
	int int_op;
	int rsock;
	int ssock;

	if ((pe = getprotobyname(pr->icmp)) == NULL) {
		Fprintf(stderr, "%s: unknown protocol %s\n", prog, pr->icmp);
		exit(EXIT_FAILURE);
	}

	/* privilege bracketing */
	(void) __priv_bracket(PRIV_ON);

	if ((rsock = socket(pr->family, SOCK_RAW, pe->p_proto)) < 0) {
		Fprintf(stderr, "%s: icmp socket: %s\n", prog, strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (options & SO_DEBUG) {
		if (setsockopt(rsock, SOL_SOCKET, SO_DEBUG, (char *)&on,
		    sizeof (on)) < 0) {
			Fprintf(stderr, "%s: SO_DEBUG: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	}
	if (options & SO_DONTROUTE) {
		if (setsockopt(rsock, SOL_SOCKET, SO_DONTROUTE, (char *)&on,
		    sizeof (on)) < 0) {
			Fprintf(stderr, "%s: SO_DONTROUTE: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	if (pr->family == AF_INET6) {
		/* Enable receipt of destination address info */
		if (setsockopt(rsock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
		    (char *)&on, sizeof (on)) < 0) {
			Fprintf(stderr, "%s: IPV6_RECVPKTINFO: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
		/* Enable receipt of hoplimit info */
		if (setsockopt(rsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
		    (char *)&on, sizeof (on)) < 0) {
			Fprintf(stderr, "%s: IPV6_RECVHOPLIMIT: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}

	}

	/*
	 * Initialize the socket type and protocol based on the address
	 * family, whether or not a raw IP socket is required (for IPv4)
	 * or whether ICMP will be used instead of UDP.
	 *
	 * For historical reasons, the datagrams sent out by
	 * traceroute(8) do not have the "don't fragment" flag set.  For
	 * this reason as well as the ability to set the Loose Source and
	 * Record Route (LSRR) option, a raw IP socket will be used for
	 * IPv4 when run in the global zone.  Otherwise, the actual
	 * datagram that will be sent will be a regular UDP or ICMP echo
	 * request packet.  However for convenience and for future options
	 * when other IP header information may be specified using
	 * traceroute, the buffer including the raw IP and UDP or ICMP
	 * header is always filled in.  When the probe is actually sent,
	 * the size of the request and the start of the packet is set
	 * according to the type of datagram to send.
	 */
	if (pr->family == AF_INET && raw_req) {
		type = SOCK_RAW;
		proto = IPPROTO_RAW;
	} else if (useicmp) {
		type = SOCK_RAW;
		if (pr->family == AF_INET)
			proto = IPPROTO_ICMP;
		else
			proto = IPPROTO_ICMPV6;
	} else {
		type = SOCK_DGRAM;
		proto = IPPROTO_UDP;
	}
	ssock = socket(pr->family, type, proto);

	if (ssock < 0) {
		if (proto == IPPROTO_RAW) {
			Fprintf(stderr, "%s: raw socket: %s\n", prog,
			    strerror(errno));
		} else if (proto == IPPROTO_UDP) {
			Fprintf(stderr, "%s: udp socket: %s\n", prog,
			    strerror(errno));
		} else {
			Fprintf(stderr, "%s: icmp socket: %s\n", prog,
			    strerror(errno));
		}
		exit(EXIT_FAILURE);
	}

	if (setsockopt(ssock, SOL_SOCKET, SO_SNDBUF, (char *)&packet_len,
	    sizeof (packet_len)) < 0) {
		Fprintf(stderr, "%s: SO_SNDBUF: %s\n", prog, strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (pr->family == AF_INET && raw_req) {
		if (setsockopt(ssock, IPPROTO_IP, IP_HDRINCL, (char *)&on,
		    sizeof (on)) < 0) {
			Fprintf(stderr, "%s: IP_HDRINCL: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	if (options & SO_DEBUG) {
		if (setsockopt(ssock, SOL_SOCKET, SO_DEBUG, (char *)&on,
		    sizeof (on)) < 0) {
			Fprintf(stderr, "%s: SO_DEBUG: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	}
	if (options & SO_DONTROUTE) {
		if (setsockopt(ssock, SOL_SOCKET, SO_DONTROUTE,
		    (char *)&on, sizeof (on)) < 0) {
			Fprintf(stderr, "%s: SO_DONTROUTE: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	/*
	 * If a raw IPv4 packet is going to be sent, the Type of Service
	 * field in the packet will be initialized in set_buffers().
	 * Otherwise, it is initialized here using the IPPROTO_IP level
	 * socket option.
	 */
	if (settos && !raw_req) {
		int_op = tos;
		if (setsockopt(ssock, IPPROTO_IP, IP_TOS, (char *)&int_op,
		    sizeof (int_op)) < 0) {
			Fprintf(stderr, "%s: IP_TOS: %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	/* We enable or disable to not depend on the kernel default */
	if (pr->family == AF_INET) {
		if (setsockopt(ssock, IPPROTO_IP, IP_DONTFRAG,
		    (char *)&dontfrag, sizeof (dontfrag)) == -1) {
			Fprintf(stderr, "%s: IP_DONTFRAG %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	} else {
		if (setsockopt(ssock, IPPROTO_IPV6, IPV6_DONTFRAG,
		    (char *)&dontfrag, sizeof (dontfrag)) == -1) {
			Fprintf(stderr, "%s: IPV6_DONTFRAG %s\n", prog,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	if (pr->family == AF_INET) {
		rcvsock4 = rsock;
		sndsock4 = ssock;
	} else {
		rcvsock6 = rsock;
		sndsock6 = ssock;
	}
	/* Revert to non-privileged user after configuring sockets */
	(void) __priv_bracket(PRIV_OFF);
}

/*
 * If we are "probing all", this function calls traceroute() for each IP address
 * of the target, otherwise calls only once. Returns _B_FALSE if traceroute()
 * fails.
 */
static void
trace_it(struct addrinfo *ai_dst)
{
	struct msghdr msg6;
	int num_dst_IPaddrs;
	struct addrinfo *aip;
	int i;

	if (!probe_all)
		num_dst_IPaddrs = 1;
	else
		num_dst_IPaddrs = num_v4 + num_v6;

	/*
	 * Initialize the msg6 structure using the hoplimit for the first
	 * probe packet, gateway addresses and the outgoing interface index.
	 */
	if (ai_dst->ai_family == AF_INET6 || (probe_all && num_v6)) {
		msg6.msg_control = NULL;
		msg6.msg_controllen = 0;
		set_ancillary_data(&msg6, first_ttl, pr6->gwIPlist, gw_count,
		    if_index);
	}

	/* run traceroute for all the IP addresses of the multihomed dest */
	for (aip = ai_dst, i = 0; i < num_dst_IPaddrs && aip != NULL; i++) {
		union any_in_addr *addrp;
		if (aip->ai_family == AF_INET) {
			addrp = (union any_in_addr *)
			    /* LINTED E_BAD_PTR_CAST_ALIGN */
			    &((struct sockaddr_in *)
			    aip->ai_addr)->sin_addr;
			set_sin((struct sockaddr *)pr4->to, addrp,
			    aip->ai_family);
			traceroute(addrp, &msg6, pr4, num_ifs4, al4);
		} else {
			addrp = (union any_in_addr *)
			    /* LINTED E_BAD_PTR_CAST_ALIGN */
			    &((struct sockaddr_in6 *)
			    aip->ai_addr)->sin6_addr;
			set_sin((struct sockaddr *)pr6->to, addrp,
			    aip->ai_family);
			traceroute(addrp, &msg6, pr6, num_ifs6, al6);
		}
		aip = aip->ai_next;
		if (i < (num_dst_IPaddrs - 1))
			(void) putchar('\n');
	}
}

/*
 * set the IP address in a sockaddr struct
 */
static void
set_sin(struct sockaddr *sock, union any_in_addr *addr, int family)
{
	sock->sa_family = family;

	if (family == AF_INET)
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		((struct sockaddr_in *)sock)->sin_addr = addr->addr;
	else
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		((struct sockaddr_in6 *)sock)->sin6_addr = addr->addr6;
}

/*
 * returns the IF name on which the given IP address is configured
 */
static char *
device_name(struct ifaddrlist *al, int len, union any_in_addr *ip_addr,
    struct pr_set *pr)
{
	int i;
	struct ifaddrlist *tmp_al;

	tmp_al = al;

	for (i = 0; i < len; i++, tmp_al++) {
		if (memcmp(&tmp_al->addr, ip_addr, pr->addr_len) == 0) {
			return (tmp_al->device);
		}
	}

	return (NULL);
}

/*
 * Trace the route to the host with given IP address.
 */
static void
traceroute(union any_in_addr *ip_addr, struct msghdr *msg6, struct pr_set *pr,
    int num_ifs, struct ifaddrlist *al)
{
	int ttl;
	int probe;
	uchar_t type;				/* icmp type */
	uchar_t code;				/* icmp code */
	int reply;
	int seq = 0;
	char abuf[INET6_ADDRSTRLEN];		/* use for inet_ntop() */
	int longjmp_return;			/* return value from longjump */
	struct ip *ip = (struct ip *)packet;
	boolean_t got_there = _B_FALSE;		/* we hit the destination */
	static boolean_t first_pkt = _B_TRUE;
	int hoplimit;				/* hoplimit for IPv6 packets */
	struct in6_addr addr6;
	int num_src_ifs;			/* excludes down and loopback */
	struct msghdr in_msg;
	struct iovec iov;
	int *intp;
	int sndsock;
	int rcvsock;

	msg6->msg_name = pr->to;
	msg6->msg_namelen = sizeof (struct sockaddr_in6);
	sndsock =  (pr->family == AF_INET) ? sndsock4 : sndsock6;
	rcvsock =  (pr->family == AF_INET) ? rcvsock4 : rcvsock6;

	/* carry out the source address selection */
	if (pick_src) {
		union any_in_addr src_addr;
		char *dev_name;
		int i;

		/*
		 * If there's a gateway, a routing header as a consequence, our
		 * kernel picks the source address based on the first hop
		 * address, rather than final destination address.
		 */
		if (gw_count > 0) {
			(void) select_src_addr(pr->gwIPlist, &src_addr,
			    pr->family);
		} else {
			(void) select_src_addr(ip_addr, &src_addr, pr->family);
		}
		set_sin(pr->from, &src_addr, pr->family);

		/* filter out down and loopback interfaces */
		num_src_ifs = 0;
		for (i = 0; i < num_ifs; i++) {
			if (!(al[i].flags & IFF_LOOPBACK) &&
			    (al[i].flags & IFF_UP))
				num_src_ifs++;
		}

		if (num_src_ifs > 1) {
			dev_name = device_name(al, num_ifs, &src_addr, pr);
			if (dev_name == NULL)
				dev_name = "?";

			(void) inet_ntop(pr->family, pr->from_sin_addr, abuf,
			    sizeof (abuf));
			Fprintf(stderr,
			    "%s: Warning: Multiple interfaces found;"
			    " using %s @ %s\n", prog, abuf, dev_name);
		}
	}

	if (pr->family == AF_INET) {
		outip4->ip_src = *(struct in_addr *)pr->from_sin_addr;
		outip4->ip_dst = ip_addr->addr;
	}

	/*
	 * If the hostname is an IPv6 literal address, let's not print it twice.
	 */
	if (pr->family == AF_INET6 &&
	    inet_pton(AF_INET6, hostname, &addr6) > 0) {
		Fprintf(stderr, "%s to %s", prog, hostname);
	} else {
		Fprintf(stderr, "%s to %s (%s)", prog, hostname,
		    inet_ntop(pr->family, ip_addr, abuf, sizeof (abuf)));
	}

	if (source)
		Fprintf(stderr, " from %s", source);
	Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl,
	    pr->packlen);
	(void) fflush(stderr);

	/*
	 * Setup the source routing for IPv4. For IPv6, we did the required
	 * setup in the caller function, trace_it(), because it's independent
	 * from the IP address of target.
	 */
	if (pr->family == AF_INET && gw_count > 0)
		set_IPv4opt_sourcerouting(sndsock, ip_addr, pr->gwIPlist);

	if (probe_all) {
		/* interrupt handler sig_handler() jumps back to here */
		if ((longjmp_return = setjmp(env)) != 0) {
			switch (longjmp_return) {
			case SIGINT:
				Printf("(skipping)\n");
				return;
			case SIGQUIT:
				Printf("(exiting)\n");
				exit(EXIT_SUCCESS);
			default:	/* should never happen */
				exit(EXIT_FAILURE);
			}
		}
		(void) signal(SIGINT, sig_handler);
	}

	for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
		union any_in_addr lastaddr;
		int timeouts = 0;
		double rtt;		/* for statistics */
		int nreceived = 0;
		double rttmin, rttmax;
		double rttsum, rttssq;
		int unreachable;

		got_there = _B_FALSE;
		unreachable = 0;

		/*
		 * The following line clears both IPv4 and IPv6 address stored
		 * in the union.
		 */
		lastaddr.addr6 = in6addr_any;

		if ((ttl == (first_ttl + 1)) && (options & SO_DONTROUTE)) {
			Fprintf(stderr,
			    "%s: host %s is not on a directly-attached"
			    " network\n", prog, hostname);
			break;
		}

		Printf("%2d ", ttl);
		(void) fflush(stdout);

		for (probe = 0; (probe < nprobes) && (timeouts < max_timeout);
		    ++probe) {
			int cc;
			struct timeval t1, t2;

			/*
			 * Put a delay before sending this probe packet. Don't
			 * delay it if it's the very first packet.
			 */
			if (!first_pkt) {
				if (delay.tv_sec > 0)
					(void) sleep((uint_t)delay.tv_sec);
				if (delay.tv_usec > 0)
					(void) usleep(delay.tv_usec);
			} else {
				first_pkt = _B_FALSE;
			}

			(void) gettimeofday(&t1, NULL);

			if (pr->family == AF_INET) {
				send_probe(sndsock, pr->to, outip4, seq, ttl,
				    &t1, pr->packlen);
			} else {
				send_probe6(sndsock, msg6, outip6, seq, ttl,
				    &t1, pr->packlen);
			}

			/* prepare msghdr for recvmsg() */
			in_msg.msg_name = pr->from;
			in_msg.msg_namelen = pr->sock_size;

			iov.iov_base = (char *)packet;
			iov.iov_len = sizeof (packet);

			in_msg.msg_iov = &iov;
			in_msg.msg_iovlen = 1;

			in_msg.msg_control = ancillary_data;
			in_msg.msg_controllen = sizeof (ancillary_data);

			while ((cc = wait_for_reply(rcvsock, &in_msg,
			    &t1)) != 0) {
				(void) gettimeofday(&t2, NULL);

				reply = (*pr->check_reply_fn) (&in_msg, cc, seq,
				    &type, &code);

				in_msg.msg_controllen =
				    sizeof (ancillary_data);
				/* Skip short packet */
				if (reply == REPLY_SHORT_PKT) {
					continue;
				}

				timeouts = 0;

				/*
				 * if reply comes from a different host, print
				 * the hostname
				 */
				if (memcmp(pr->from_sin_addr, &lastaddr,
				    pr->addr_len) != 0) {
					(*pr->print_addr_fn) ((uchar_t *)packet,
					    cc, pr->from);
					/* store the address response */
					(void) memcpy(&lastaddr,
					    pr->from_sin_addr, pr->addr_len);
				}

				rtt = deltaT(&t1, &t2);
				if (collect_stat) {
					record_stats(rtt, &nreceived, &rttmin,
					    &rttmax, &rttsum, &rttssq);
				} else {
					Printf("  %.3f ms", rtt);
				}

				if (pr->family == AF_INET6) {
					intp = find_ancillary_data(&in_msg,
					    IPPROTO_IPV6, IPV6_HOPLIMIT);
					if (intp == NULL) {
						Fprintf(stderr,
						    "%s: can't find "
						    "IPV6_HOPLIMIT ancillary "
						    "data\n", prog);
						exit(EXIT_FAILURE);
					}
					hoplimit = *intp;
				}

				if (reply == REPLY_GOT_TARGET) {
					got_there = _B_TRUE;

					if (((pr->family == AF_INET) &&
					    (ip->ip_ttl <= 1)) ||
					    ((pr->family == AF_INET6) &&
					    (hoplimit <= 1)))
						Printf(" !");
				}

				if (!collect_stat && showttl) {
					if (pr->family == AF_INET) {
						Printf(" (ttl=%d)",
						    (int)ip->ip_ttl);
					} else if (hoplimit != -1) {
						Printf(" (hop limit=%d)",
						    hoplimit);
					}
				}

				if (reply == REPLY_GOT_OTHER) {
					if ((*pr->print_icmp_other_fn)
					    (type, code)) {
						unreachable++;
					}
				}

				/* special case */
				if (pr->family == AF_INET &&
				    type == ICMP_UNREACH &&
				    code == ICMP_UNREACH_PROTOCOL)
					got_there = _B_TRUE;

				break;
			}

			seq = (seq + 1) % (MAX_SEQ + 1);

			if (cc == 0) {
				Printf(" *");
				timeouts++;
			}

			(void) fflush(stdout);
		}

		if (collect_stat) {
			print_stats(probe, nreceived, rttmin, rttmax, rttsum,
			    rttssq);
		}

		(void) putchar('\n');

		/* either we hit the target or received too many unreachables */
		if (got_there ||
		    (unreachable > 0 && unreachable >= nprobes - 1))
			break;
	}

	/* Ignore the SIGINT between traceroute() runs */
	if (probe_all)
		(void) signal(SIGINT, SIG_IGN);
}

/*
 * for a given destination address and address family, it finds out what
 * source address kernel is going to pick
 */
static void
select_src_addr(union any_in_addr *dst_addr, union any_in_addr *src_addr,
    int family)
{
	int tmp_fd;
	struct sockaddr *sock;
	struct sockaddr_in *sin;
	struct sockaddr_in6 *sin6;
	size_t sock_len;

	sock = (struct sockaddr *)malloc(sizeof (struct sockaddr_in6));
	if (sock == NULL) {
		Fprintf(stderr, "%s: malloc %s\n", prog, strerror(errno));
		exit(EXIT_FAILURE);
	}
	(void) bzero(sock, sizeof (struct sockaddr_in6));

	if (family == AF_INET) {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin = (struct sockaddr_in *)sock;
		sin->sin_family = AF_INET;
		sin->sin_addr = dst_addr->addr;
		sin->sin_port = IPPORT_ECHO;	/* port shouldn't be 0 */
		sock_len = sizeof (struct sockaddr_in);
	} else {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin6 = (struct sockaddr_in6 *)sock;
		sin6->sin6_family = AF_INET6;
		sin6->sin6_addr = dst_addr->addr6;
		sin6->sin6_port = IPPORT_ECHO;	/* port shouldn't be 0 */
		sock_len = sizeof (struct sockaddr_in6);
	}

	/* open a UDP socket */
	if ((tmp_fd = socket(family, SOCK_DGRAM, 0)) < 0) {
		Fprintf(stderr, "%s: udp socket: %s\n", prog,
		    strerror(errno));
		exit(EXIT_FAILURE);
	}

	/* connect it */
	if (connect(tmp_fd, sock, sock_len) < 0) {
		/*
		 * If there's no route to the destination, this connect() call
		 * fails. We just return all-zero (wildcard) as the source
		 * address, so that user can get to see "no route to dest"
		 * message, as it'll try to send the probe packet out and will
		 * receive ICMP unreachable.
		 */
		if (family == AF_INET)
			src_addr->addr.s_addr = INADDR_ANY;
		else
			src_addr->addr6 = in6addr_any;
		free(sock);
		return;
	}

	/* get the local sock info */
	if (getsockname(tmp_fd, sock, &sock_len) < 0) {
		Fprintf(stderr, "%s: getsockname: %s\n", prog,
		    strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (family == AF_INET) {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin = (struct sockaddr_in *)sock;
		src_addr->addr = sin->sin_addr;
	} else {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin6 = (struct sockaddr_in6 *)sock;
		src_addr->addr6 = sin6->sin6_addr;
	}

	free(sock);
	(void) close(tmp_fd);
}

/*
 * Checksum routine for Internet Protocol family headers (C Version)
 */
ushort_t
in_cksum(ushort_t *addr, int len)
{
	int nleft = len;
	ushort_t *w = addr;
	ushort_t answer;
	int sum = 0;

	/*
	 *  Our algorithm is simple, using a 32 bit accumulator (sum),
	 *  we add sequential 16 bit words to it, and at the end, fold
	 *  back all the carry bits from the top 16 bits into the lower
	 *  16 bits.
	 */
	while (nleft > 1)  {
		sum += *w++;
		nleft -= 2;
	}

	/* mop up an odd byte, if necessary */
	if (nleft == 1)
		sum += *(uchar_t *)w;

	/* add back carry outs from top 16 bits to low 16 bits */
	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
	sum += (sum >> 16);			/* add carry */
	answer = ~sum;				/* truncate to 16 bits */
	return (answer);
}

/*
 * Wait until a reply arrives or timeout occurs. If packet arrived, read it
 * return the size of the packet read.
 */
static int
wait_for_reply(int sock, struct msghdr *msg, struct timeval *tp)
{
	fd_set fds;
	struct timeval now, wait;
	int cc = 0;
	int result;

	(void) FD_ZERO(&fds);
	FD_SET(sock, &fds);

	wait.tv_sec = tp->tv_sec + waittime;
	wait.tv_usec = tp->tv_usec;
	(void) gettimeofday(&now, NULL);
	tv_sub(&wait, &now);

	if (wait.tv_sec < 0 || wait.tv_usec < 0)
		return (0);

	result = select(sock + 1, &fds, (fd_set *)NULL, (fd_set *)NULL, &wait);

	if (result == -1) {
		if (errno != EINTR) {
			Fprintf(stderr, "%s: select: %s\n", prog,
			    strerror(errno));
		}
	} else if (result > 0)
		cc = recvmsg(sock, msg, 0);

	return (cc);
}

/*
 * Construct an Internet address representation. If the nflag has been supplied,
 * give numeric value, otherwise try for symbolic name.
 */
char *
inet_name(union any_in_addr *in, int family)
{
	char *cp;
	static boolean_t first = _B_TRUE;
	static char domain[NI_MAXHOST + 1];
	static char line[NI_MAXHOST + 1];	/* assuming		*/
				/* (NI_MAXHOST + 1) >= INET6_ADDRSTRLEN */
	char hbuf[NI_MAXHOST];
	socklen_t slen;
	struct sockaddr_in sin;
	struct sockaddr_in6 sin6;
	struct sockaddr *sa;
	int flags;

	switch (family) {
	case AF_INET:
		slen = sizeof (struct sockaddr_in);
		sin.sin_addr = in->addr;
		sin.sin_port = 0;
		sa = (struct sockaddr *)&sin;
		break;
	case AF_INET6:
		slen = sizeof (struct sockaddr_in6);
		sin6.sin6_addr = in->addr6;
		sin6.sin6_port = 0;
		sin6.sin6_scope_id = 0;
		sa = (struct sockaddr *)&sin6;
		break;
	default:
		(void) snprintf(line, sizeof (line),
		    "<invalid address family>");
		return (line);
	}
	sa->sa_family = family;

	if (first && !nflag) {
		/* find out the domain name */
		first = _B_FALSE;
		mutex_enter(&tr_nslock);
		tr_nsactive = _B_TRUE;
		tr_nsstarttime = gethrtime();
		mutex_exit(&tr_nslock);
		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
		    (cp = strchr(domain, '.')) != NULL) {
			(void) strncpy(domain, cp + 1, sizeof (domain) - 1);
			domain[sizeof (domain) - 1] = '\0';
		} else {
			domain[0] = '\0';
		}
		mutex_enter(&tr_nslock);
		tr_nsactive = _B_FALSE;
		mutex_exit(&tr_nslock);
	}

	flags = (nflag) ? NI_NUMERICHOST : NI_NAMEREQD;
	mutex_enter(&tr_nslock);
	tr_nsactive = _B_TRUE;
	tr_nsstarttime = gethrtime();
	mutex_exit(&tr_nslock);
	if (getnameinfo(sa, slen, hbuf, sizeof (hbuf), NULL, 0, flags) != 0) {
		if (inet_ntop(family, (const void *)&in->addr6,
		    hbuf, sizeof (hbuf)) == NULL)
			hbuf[0] = 0;
	} else if (!nflag && (cp = strchr(hbuf, '.')) != NULL &&
	    strcmp(cp + 1, domain) == 0) {
		*cp = '\0';
	}
	mutex_enter(&tr_nslock);
	tr_nsactive = _B_FALSE;
	mutex_exit(&tr_nslock);
	(void) strlcpy(line, hbuf, sizeof (line));

	return (line);
}

/*
 * return the difference (in msec) between two time values
 */
static double
deltaT(struct timeval *t1p, struct timeval *t2p)
{
	double dt;

	dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
	    (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
	return (dt);
}

/*
 * Subtract 2 timeval structs:  out = out - in.
 * Out is assumed to be >= in.
 */
static void
tv_sub(struct timeval *out, struct timeval *in)
{
	if ((out->tv_usec -= in->tv_usec) < 0)   {
		--out->tv_sec;
		out->tv_usec += 1000000;
	}
	out->tv_sec -= in->tv_sec;
}

/*
 * record statistics
 */
static void
record_stats(double rtt, int *nreceived, double *rttmin, double *rttmax,
    double *rttsum, double *rttssq)
{
	if (*nreceived == 0) {
		*rttmin = rtt;
		*rttmax = rtt;
		*rttsum = rtt;
		*rttssq = rtt * rtt;
	} else {
		if (rtt < *rttmin)
			*rttmin = rtt;

		if (rtt > *rttmax)
			*rttmax = rtt;

		*rttsum += rtt;
		*rttssq += rtt * rtt;
	}

	(*nreceived)++;
}

/*
 * display statistics
 */
static void
print_stats(int ntransmitted, int nreceived, double rttmin, double rttmax,
    double rttsum, double rttssq)
{
	double rttavg;			/* average round-trip time */
	double rttstd;			/* rtt standard deviation */

	if (ntransmitted > 0 && ntransmitted >= nreceived) {
		int missed = ntransmitted - nreceived;
		double loss = 100 * (double)missed / (double)ntransmitted;

		if (nreceived > 0) {
			rttavg = rttsum / nreceived;
			rttstd = rttssq - (rttavg * rttsum);
			rttstd = xsqrt(rttstd / nreceived);

			Printf("  %.3f", rttmin);
			Printf("/%.3f", rttavg);
			Printf("/%.3f", rttmax);

			Printf(" (%.3f) ms ", rttstd);
		}

		Printf(" %d/%d pkts", nreceived, ntransmitted);

		if (nreceived == 0)
			Printf(" (100%% loss)");
		else
			Printf(" (%.2g%% loss)", loss);
	}
}

/*
 * square root function
 */
double
xsqrt(double y)
{
	double t, x;

	if (y <= 0) {
		return (0.0);
	}

	x = (y < 1.0) ? 1.0 : y;
	do {
		t = x;
		x = (t + (y/t))/2.0;
	} while (0 < x && x < t);

	return (x);
}

/*
 * String to double with optional min and max.
 */
static double
str2dbl(const char *str, const char *what, double mi, double ma)
{
	double val;
	char *ep;

	errno = 0;

	val = strtod(str, &ep);
	if (errno != 0 || *ep != '\0') {
		Fprintf(stderr, "%s: \"%s\" bad value for %s \n",
		    prog, str, what);
		exit(EXIT_FAILURE);
	}
	if (val < mi && mi >= 0) {
		Fprintf(stderr, "%s: %s must be >= %f\n", prog, what, mi);
		exit(EXIT_FAILURE);
	}
	if (val > ma && ma >= 0) {
		Fprintf(stderr, "%s: %s must be <= %f\n", prog, what, ma);
		exit(EXIT_FAILURE);
	}
	return (val);
}

/*
 * String to int with optional min and max. Handles decimal and hex.
 */
static int
str2int(const char *str, const char *what, int mi, int ma)
{
	const char *cp;
	int val;
	char *ep;

	errno = 0;

	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
		cp = str + 2;
		val = (int)strtol(cp, &ep, 16);
	} else {
		val = (int)strtol(str, &ep, 10);
	}
	if (errno != 0 || *ep != '\0') {
		Fprintf(stderr, "%s: \"%s\" bad value for %s \n",
		    prog, str, what);
		exit(EXIT_FAILURE);
	}
	if (val < mi && mi >= 0) {
		if (mi == 0) {
			Fprintf(stderr, "%s: %s must be >= %d\n",
			    prog, what, mi);
		} else {
			Fprintf(stderr, "%s: %s must be > %d\n",
			    prog, what, mi - 1);
		}
		exit(EXIT_FAILURE);
	}
	if (val > ma && ma >= 0) {
		Fprintf(stderr, "%s: %s must be <= %d\n", prog, what, ma);
		exit(EXIT_FAILURE);
	}
	return (val);
}

/*
 * This is the interrupt handler for SIGINT and SIGQUIT. It's completely handled
 * where it jumps to.
 */
static void
sig_handler(int sig)
{
	longjmp(env, sig);
}

/*
 * display the usage of traceroute
 */
static void
usage(void)
{
	Fprintf(stderr, "Usage: %s [-adFIlnSvx] [-A address_family] "
	    "[-c traffic_class]\n"
	    "\t[-f first_hop] [-g gateway [-g gateway ...]| -r] [-i iface]\n"
	    "\t[-L flow_label] [-m max_hop] [-P pause_sec] [-p port] "
	    "[-Q max_timeout]\n"
	    "\t[-q nqueries] [-s src_addr] [-t tos] [-w wait_time] host "
	    "[packetlen]\n", prog);
	exit(EXIT_FAILURE);
}

/* ARGSUSED */
static void *
ns_warning_thr(void *unused)
{
	for (;;) {
		hrtime_t now;

		(void) sleep(tr_nssleeptime);

		now = gethrtime();
		mutex_enter(&tr_nslock);
		if (tr_nsactive && now - tr_nsstarttime >=
		    tr_nswarntime * NANOSEC) {
			Fprintf(stderr, "%s: warning: responses "
			    "received, but name service lookups are "
			    "taking a while. Use %s -n to disable "
			    "name service lookups.\n",
			    prog, prog);
			mutex_exit(&tr_nslock);
			return (NULL);
		}
		mutex_exit(&tr_nslock);
	}

	/* LINTED: E_STMT_NOT_REACHED */
	return (NULL);
}