xref: /titanic_41/usr/src/cmd/cmd-inet/usr.sbin/traceroute/traceroute.c (revision 70025d765b044c6d8594bb965a2247a61e991a99)
1 /*
2  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 1988, 1989, 1991, 1994, 1995, 1996, 1997
8  *	The Regents of the University of California.  All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that: (1) source code distributions
12  * retain the above copyright notice and this paragraph in its entirety, (2)
13  * distributions including binary code include the above copyright notice and
14  * this paragraph in its entirety in the documentation or other materials
15  * provided with the distribution, and (3) all advertising materials mentioning
16  * features or use of this software display the following acknowledgement:
17  * ``This product includes software developed by the University of California,
18  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
19  * the University nor the names of its contributors may be used to endorse
20  * or promote products derived from this software without specific prior
21  * written permission.
22  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
23  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
25  *
26  *
27  * @(#)$Header: traceroute.c,v 1.49 97/06/13 02:30:23 leres Exp $ (LBL)
28  */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 #include <sys/param.h>
33 #include <sys/file.h>
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/time.h>
37 #include <sys/sysmacros.h>
38 
39 #include <netinet/in_systm.h>
40 #include <netinet/in.h>
41 #include <netinet/ip.h>
42 #include <netinet/ip_var.h>
43 #include <netinet/ip_icmp.h>
44 #include <netinet/udp.h>
45 #include <netinet/udp_var.h>
46 #include <netinet/ip6.h>
47 #include <netinet/icmp6.h>
48 
49 #include <arpa/inet.h>
50 
51 #include <ctype.h>
52 #include <errno.h>
53 #include <malloc.h>
54 #include <memory.h>
55 #include <netdb.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <strings.h>
59 #include <unistd.h>
60 #include <libintl.h>
61 #include <locale.h>
62 #include <signal.h>
63 #include <setjmp.h>
64 #include <limits.h>
65 #include <zone.h>
66 
67 #include <priv_utils.h>
68 
69 
70 #include <ifaddrlist.h>
71 #include "traceroute.h"
72 
73 #define	MAX_SEQ			65535	/* max sequence value for ICMP */
74 #define	MAX_TRAFFIC_CLASS	255	/* max traffic class for IPv6 */
75 #define	MAX_FLOW_LABEL		0xFFFFF	/* max flow label for IPv6 */
76 #define	MAX_TOS			255	/* max type-of-service for IPv4 */
77 #define	STR_LEN			30
78 
79 /* store the information about a host */
80 struct hostinfo {
81 	char *name;		/* hostname */
82 	int family;		/* address family of the IP addresses */
83 	int num_addr;			/* number of IP addresses */
84 	union any_in_addr *addrs;	/* list of IP addresses */
85 };
86 
87 /* used to store a bunch of protocol specific values */
88 struct pr_set {
89 	int family;		/* AF_INET or AF_INET6 */
90 	char name[STR_LEN];	/* "IPv4" or "IPv6" */
91 	char icmp[STR_LEN];	/* "icmp" or "ipv6-icmp" */
92 	int icmp_minlen;
93 	int addr_len;
94 	int ip_hdr_len;
95 	int packlen;
96 	int sock_size;		/* size of sockaddr_in or sockaddr_in6 */
97 	struct sockaddr *to;
98 	struct sockaddr *from;
99 	void *from_sin_addr;
100 	union any_in_addr *gwIPlist;
101 	/* pointers to v4/v6 functions */
102 	struct ip *(*set_buffers_fn) (int);
103 	int (*check_reply_fn)(struct msghdr *, int, int, uchar_t *, uchar_t *);
104 	boolean_t (*print_icmp_other_fn)(uchar_t, uchar_t);
105 	void (*print_addr_fn)(uchar_t *, int, struct sockaddr *);
106 
107 };
108 
109 /*
110  * LBNL bug fixed: in LBNL traceroute 'uchar_t packet[512];'
111  * Not sufficient to hold the complete packet for ECHO REPLY of a big probe.
112  * Packet size is reported incorrectly in such a case.
113  * Also this buffer needs to be 32 bit aligned. In the future the alignment
114  * requirement will be increased to 64 bit. So, let's use 64 bit alignment now.
115  */
116 static uint64_t packet[(IP_MAXPACKET + 1)/8];	/* received packet */
117 
118 static struct ip *outip4;	/* output buffer to send as an IPv4 datagram */
119 static struct ip *outip6;	/* output buffer to send as an IPv6 datagram */
120 
121 /* Used to store the ancillary data that comes with the received packets */
122 static uint64_t ancillary_data[(IP_MAXPACKET + 1)/8];
123 
124 /* first get the gw names, later you'll resolve them based on the family */
125 static char *gwlist[MAXMAX_GWS];		/* gateway names list */
126 static union any_in_addr gwIPlist[MAX_GWS];	/* gateway IPv4 address list */
127 static union any_in_addr gwIP6list[MAX_GWS6];	/* gateway IPv6 address list */
128 
129 static int family_input = AF_UNSPEC;	/* User supplied protocol family */
130 static int rcvsock4;		/* receive (icmp) socket file descriptor */
131 static int sndsock4;		/* send (udp/icmp) socket file descriptor */
132 static int rcvsock6;		/* receive (icmp6) socket file descriptor */
133 static int sndsock6;		/* send (udp6/icmp6) socket file descriptor */
134 int gw_count = 0;		/* number of gateways */
135 static struct sockaddr_in whereto;	/* Who to try to reach */
136 static struct sockaddr_in6 whereto6;
137 static struct sockaddr_in wherefrom;	/* Who we are */
138 static struct sockaddr_in6 wherefrom6;
139 static int packlen_input = 0;		/* user input for packlen */
140 
141 char *prog;
142 static char *source_input = NULL; /* this is user arg. source, doesn't change */
143 static char *source = NULL;	/* this gets modified after name lookup */
144 char *hostname;
145 static char *device = NULL;   	/* interface name */
146 static struct pr_set *pr4;	/* protocol info for IPv4 */
147 static struct pr_set *pr6;	/* protocol info for IPv6 */
148 static struct ifaddrlist *al4;	/* list of interfaces */
149 static struct ifaddrlist *al6;	/* list of interfaces */
150 static uint_t if_index = 0;	/* interface index */
151 static int num_v4 = 0;		/* count of IPv4 addresses */
152 static int num_v6 = 0;		/* count of IPv6 addresses */
153 static int num_ifs4 = 0;	/* count of local IPv4 interfaces */
154 static int num_ifs6 = 0;	/* count of local IPv6 interfaces */
155 
156 static int nprobes = 3;		/* number of probes */
157 static int max_ttl = 30;	/* max number of hops */
158 static int first_ttl = 1;	/* initial number of hops */
159 ushort_t ident;			/* used to authenticate replies */
160 ushort_t port = 32768 + 666;	/* start udp dest port # for probe packets */
161 
162 static int options = 0;		/* socket options */
163 boolean_t verbose = _B_FALSE;	/* verbose output */
164 static int waittime = 5;	/* time to wait for response (in seconds) */
165 static struct timeval delay = {0, 0}; /* delay between consecutive probe */
166 boolean_t nflag = _B_FALSE;	/* print addresses numerically */
167 static boolean_t showttl = _B_FALSE; /* print the ttl(hop limit) of recvd pkt */
168 boolean_t useicmp = _B_FALSE;  	/* use icmp echo instead of udp packets */
169 boolean_t docksum = _B_TRUE;	/* calculate checksums */
170 static boolean_t collect_stat = _B_FALSE;	/* print statistics */
171 boolean_t settos = _B_FALSE;   	/* set type-of-service field */
172 static int max_timeout = 5;	/* quit after this consecutive timeouts */
173 static boolean_t probe_all = _B_FALSE;	/* probe all the IFs of the target */
174 static boolean_t pick_src = _B_FALSE;	/* traceroute picks the src address */
175 
176 /*
177  * flow and class are specific to IPv6, tos and off are specific to IPv4.
178  * Each protocol uses the ones that are specific to itself, and ignores
179  * others.
180  */
181 static uint_t flow = 0;		/* IPv6 flow info */
182 static uint_t class = 0;	/* IPv6 class */
183 uchar_t tos = 0;		/* IPv4 type-of-service */
184 ushort_t off = 0;		/* set DF bit */
185 
186 static jmp_buf env;		/* stack environment for longjmp() */
187 boolean_t raw_req;		/* if sndsock for IPv4 must be raw */
188 
189 /* Forwards */
190 static uint_t calc_packetlen(int, struct pr_set *);
191 extern int check_reply(struct msghdr *, int, int, uchar_t *, uchar_t *);
192 extern int check_reply6(struct msghdr *, int, int, uchar_t *, uchar_t *);
193 static double deltaT(struct timeval *, struct timeval *);
194 static char *device_name(struct ifaddrlist *, int, union any_in_addr *,
195     struct pr_set *);
196 extern void *find_ancillary_data(struct msghdr *, int, int);
197 static boolean_t has_addr(struct addrinfo *, union any_in_addr *);
198 static struct ifaddrlist *find_device(struct ifaddrlist *, int, char *);
199 static struct ifaddrlist *find_ifaddr(struct ifaddrlist *, int,
200     union any_in_addr *, int);
201 static void get_gwaddrs(char **, int, union any_in_addr *,
202     union any_in_addr *, int *, int *);
203 static void get_hostinfo(char *, int, struct addrinfo **);
204 char *inet_name(union any_in_addr *, int);
205 ushort_t in_cksum(ushort_t *, int);
206 extern int ip_hdr_length_v6(ip6_t *, int, uint8_t *);
207 extern char *pr_type(uchar_t);
208 extern char *pr_type6(uchar_t);
209 extern void print_addr(uchar_t *, int, struct sockaddr *);
210 extern void print_addr6(uchar_t *, int, struct sockaddr *);
211 extern boolean_t print_icmp_other(uchar_t, uchar_t);
212 extern boolean_t print_icmp_other6(uchar_t, uchar_t);
213 static void print_stats(int, int, double, double, double, double);
214 static void print_unknown_host_msg(const char *, const char *);
215 static void record_stats(double, int *, double *, double *, double *, double *);
216 static void resolve_nodes(int *, struct addrinfo **);
217 static void select_src_addr(union any_in_addr *, union any_in_addr *, int);
218 extern void send_probe(int, struct sockaddr *, struct ip *, int, int,
219     struct timeval *, int);
220 extern void send_probe6(int, struct msghdr *, struct ip *, int, int,
221     struct timeval *, int);
222 extern void set_ancillary_data(struct msghdr *, int, union any_in_addr *, int,
223     uint_t);
224 extern struct ip *set_buffers(int);
225 extern struct ip *set_buffers6(int);
226 extern void set_IPv4opt_sourcerouting(int, union any_in_addr *,
227     union any_in_addr *);
228 static void set_sin(struct sockaddr *, union any_in_addr *, int);
229 static int set_src_addr(struct pr_set *, struct ifaddrlist **);
230 static void setup_protocol(struct pr_set *, int);
231 static void setup_socket(struct pr_set *, int);
232 static void sig_handler(int);
233 static int str2int(const char *, const char *, int, int);
234 static double str2dbl(const char *, const char *, double, double);
235 static void trace_it(struct addrinfo *);
236 static void traceroute(union any_in_addr *, struct msghdr *, struct pr_set *,
237     int, struct ifaddrlist *);
238 static void tv_sub(struct timeval *, struct timeval *);
239 static void usage(void);
240 static int wait_for_reply(int, struct msghdr *, struct timeval *);
241 static double xsqrt(double);
242 
243 /*
244  * main
245  */
246 int
247 main(int argc, char **argv)
248 {
249 	struct addrinfo *ai_dst = NULL;		/* destination host */
250 	/*
251 	 * "probing_successful" indicates if we could successfully send probes,
252 	 * not necessarily received reply from the target (this behavior is from
253 	 * the original traceroute). It's _B_FALSE if packlen is invalid, or no
254 	 * interfaces found.
255 	 */
256 	boolean_t probing_successful = _B_FALSE;
257 	int longjmp_return;			/* return value from longjump */
258 	int i = 0;
259 	char *cp;
260 	int op;
261 	char *ep;
262 	char temp_buf[INET6_ADDRSTRLEN];	/* use for inet_ntop() */
263 	double pause;
264 
265 	/*
266 	 * A raw socket will be used for IPv4 if there is sufficient
267 	 * privilege.
268 	 */
269 	raw_req = priv_ineffect(PRIV_NET_RAWACCESS);
270 
271 	/*
272 	 * We'll need the privilege only when we open the sockets; that's
273 	 * when we'll fail if the program has insufficient privileges.
274 	 */
275 	(void) __init_suid_priv(PU_CLEARLIMITSET, PRIV_NET_ICMPACCESS,
276 	    raw_req ? PRIV_NET_RAWACCESS : NULL, NULL);
277 
278 	(void) setlinebuf(stdout);
279 
280 	if ((cp = strrchr(argv[0], '/')) != NULL)
281 		prog = cp + 1;
282 	else
283 		prog = argv[0];
284 
285 	opterr = 0;
286 	while ((op = getopt(argc, argv, "adFIlnrSvxA:c:f:g:i:L:m:P:p:Q:q:s:"
287 	    "t:w:")) != EOF) {
288 		switch (op) {
289 		case 'A':
290 			if (strcmp(optarg, "inet") == 0) {
291 				family_input = AF_INET;
292 			} else if (strcmp(optarg, "inet6") == 0) {
293 				family_input = AF_INET6;
294 			} else {
295 				Fprintf(stderr,
296 				    "%s: unknown address family %s\n",
297 				    prog, optarg);
298 				exit(EXIT_FAILURE);
299 			}
300 			break;
301 
302 		case 'a':
303 			probe_all = _B_TRUE;
304 			break;
305 
306 		case 'c':
307 			class = str2int(optarg, "traffic class", 0,
308 			    MAX_TRAFFIC_CLASS);
309 			break;
310 
311 		case 'd':
312 			options |= SO_DEBUG;
313 			break;
314 
315 		case 'f':
316 			first_ttl = str2int(optarg, "first ttl", 1, MAXTTL);
317 			break;
318 
319 		case 'F':
320 			off = IP_DF;
321 			break;
322 
323 		case 'g':
324 			if (!raw_req) {
325 				Fprintf(stderr,
326 				    "%s: privilege to specify a loose source "
327 				    "route gateway is unavailable\n",
328 				    prog);
329 				exit(EXIT_FAILURE);
330 			}
331 			if (gw_count >= MAXMAX_GWS) {
332 				Fprintf(stderr,
333 				    "%s: Too many gateways\n", prog);
334 				exit(EXIT_FAILURE);
335 			}
336 			gwlist[gw_count] = strdup(optarg);
337 			if (gwlist[gw_count] == NULL) {
338 				Fprintf(stderr, "%s: strdup %s\n", prog,
339 				    strerror(errno));
340 				exit(EXIT_FAILURE);
341 			}
342 
343 			++gw_count;
344 			break;
345 
346 		case 'l':
347 			showttl = _B_TRUE;
348 			break;
349 
350 		case 'i':
351 			/* this can be IF name or IF index */
352 			if_index = (uint_t)strtol(optarg, &ep, 10);
353 
354 			/* convert IF index <-->  IF name */
355 			if (errno != 0 || *ep != '\0') {
356 				device = optarg;
357 				if_index = if_nametoindex((const char *)device);
358 
359 				/*
360 				 * In case it fails, check to see if the problem
361 				 * is other than "IF not found".
362 				 */
363 				if (if_index == 0 && errno != ENXIO) {
364 					Fprintf(stderr, "%s: if_nametoindex:"
365 					    "%s\n", prog, strerror(errno));
366 					exit(EXIT_FAILURE);
367 				}
368 			} else {
369 				device = (char *)malloc(LIFNAMSIZ + 1);
370 				if (device == NULL) {
371 					Fprintf(stderr, "%s: malloc: %s\n",
372 					    prog, strerror(errno));
373 					exit(EXIT_FAILURE);
374 				}
375 
376 				device = if_indextoname(if_index, device);
377 				if (device != NULL) {
378 					device[LIFNAMSIZ] = '\0';
379 				} else if (errno != ENXIO) {
380 					/*
381 					 * The problem was other than "index
382 					 * not found".
383 					 */
384 					Fprintf(stderr, "%s: if_indextoname:"
385 					    "%s\n", prog, strerror(errno));
386 					exit(EXIT_FAILURE);
387 				}
388 			}
389 
390 			if (device == NULL || if_index == 0) {
391 				Fprintf(stderr, "%s: interface %s "
392 				    "doesn't match any actual interfaces\n",
393 				    prog, optarg);
394 				exit(EXIT_FAILURE);
395 			}
396 			break;
397 
398 		case 'I':
399 			useicmp = _B_TRUE;
400 			break;
401 
402 		case 'L':
403 			flow = str2int(optarg, "flow label", 0, MAX_FLOW_LABEL);
404 			break;
405 
406 		case 'm':
407 			max_ttl = str2int(optarg, "max ttl(hop limit)", 1,
408 			    MAXTTL);
409 			break;
410 
411 		case 'n':
412 			nflag = _B_TRUE;
413 			break;
414 
415 		case 'P':
416 			pause = str2dbl(optarg, "pause", 0, INT_MAX);
417 			delay.tv_sec = (time_t)pause;
418 			delay.tv_usec = (suseconds_t)((pause - delay.tv_sec) *
419 			    1000000);
420 			break;
421 
422 		case 'p':
423 			port = str2int(optarg, "port", 1, MAX_PORT);
424 			break;
425 
426 		case 'Q':
427 			max_timeout = str2int(optarg, "max timeout", 1, -1);
428 			break;
429 
430 		case 'q':
431 			nprobes = str2int(optarg, "nprobes", 1, -1);
432 			break;
433 
434 		case 'r':
435 			options |= SO_DONTROUTE;
436 			break;
437 
438 		case 'S':
439 			collect_stat = _B_TRUE;
440 			break;
441 
442 		case 's':
443 			/*
444 			 * set the ip source address of the outbound
445 			 * probe (e.g., on a multi-homed host).
446 			 */
447 			source_input = optarg;
448 			break;
449 
450 		case 't':
451 			tos = (uchar_t)str2int(optarg, "tos", 0, MAX_TOS);
452 			settos = _B_TRUE;
453 			break;
454 
455 		case 'v':
456 			verbose = _B_TRUE;
457 			break;
458 
459 		case 'x':
460 			docksum = _B_FALSE;
461 			break;
462 
463 		case 'w':
464 			waittime = str2int(optarg, "wait time", 2, -1);
465 			break;
466 
467 		default:
468 			usage();
469 			break;
470 		}
471 	}
472 
473 	/*
474 	 * If it's probe_all, SIGQUIT makes traceroute exit(). But we set the
475 	 * address to jump back to in traceroute(). Until then, we'll need to
476 	 * temporarily specify one.
477 	 */
478 	if (probe_all) {
479 		if ((longjmp_return = setjmp(env)) != 0) {
480 			if (longjmp_return == SIGQUIT) {
481 				Printf("(exiting)\n");
482 				exit(EXIT_SUCCESS);
483 			} else {		/* should never happen */
484 				exit(EXIT_FAILURE);
485 			}
486 		}
487 		(void) signal(SIGQUIT, sig_handler);
488 	}
489 
490 	if ((gw_count > 0) && (options & SO_DONTROUTE)) {
491 		Fprintf(stderr, "%s: loose source route gateways (-g)"
492 		    " cannot be specified when probe packets are sent"
493 		    " directly to a host on an attached network (-r)\n",
494 		    prog);
495 		exit(EXIT_FAILURE);
496 	}
497 
498 	i = argc - optind;
499 	if (i == 1 || i == 2) {
500 		hostname = argv[optind];
501 
502 		if (i == 2) {
503 			/* accept any length now, we'll check it later */
504 			packlen_input = str2int(argv[optind + 1],
505 			    "packet length", 0, -1);
506 		}
507 	} else {
508 		usage();
509 	}
510 
511 	if (first_ttl > max_ttl) {
512 		Fprintf(stderr,
513 		    "%s: first ttl(hop limit) (%d) may not be greater"
514 		    " than max ttl(hop limit) (%d)\n",
515 		    prog, first_ttl, max_ttl);
516 		exit(EXIT_FAILURE);
517 	}
518 
519 	/* resolve hostnames */
520 	resolve_nodes(&family_input, &ai_dst);
521 	if (ai_dst == NULL) {
522 		exit(EXIT_FAILURE);
523 	}
524 
525 	/*
526 	 * If it's probe_all, SIGINT makes traceroute skip to probing next IP
527 	 * address of the target. The new interrupt handler is assigned in
528 	 * traceroute() function. Until then let's ignore the signal.
529 	 */
530 	if (probe_all)
531 		(void) signal(SIGINT, SIG_IGN);
532 
533 	ident = (getpid() & 0xffff) | 0x8000;
534 
535 	/*
536 	 * We KNOW that probe_all == TRUE if family is AF_UNSPEC,
537 	 * since family is set to the specific AF found unless it's
538 	 * probe_all. So if family == AF_UNSPEC, we need to init pr4 and pr6.
539 	 */
540 	switch (family_input) {
541 	case AF_UNSPEC:
542 		pr4 = (struct pr_set *)malloc(sizeof (struct pr_set));
543 		if (pr4 == NULL) {
544 			Fprintf(stderr,
545 			    "%s: malloc %s\n", prog, strerror(errno));
546 			exit(EXIT_FAILURE);
547 		}
548 		pr6 = (struct pr_set *)malloc(sizeof (struct pr_set));
549 		if (pr6 == NULL) {
550 			Fprintf(stderr,
551 			    "%s: malloc %s\n", prog, strerror(errno));
552 			exit(EXIT_FAILURE);
553 		}
554 		setup_protocol(pr6, AF_INET6);
555 		setup_protocol(pr4, AF_INET);
556 		outip6 = (*pr6->set_buffers_fn)(pr6->packlen);
557 		setup_socket(pr6, pr6->packlen);
558 
559 		outip4 = (*pr4->set_buffers_fn)(pr4->packlen);
560 		setup_socket(pr4, pr4->packlen);
561 		num_ifs6 = set_src_addr(pr6, &al6);
562 		num_ifs4 = set_src_addr(pr4, &al4);
563 		break;
564 	case AF_INET6:
565 		pr6 = (struct pr_set *)malloc(sizeof (struct pr_set));
566 		if (pr6 == NULL) {
567 			Fprintf(stderr,
568 			    "%s: malloc %s\n", prog, strerror(errno));
569 			exit(EXIT_FAILURE);
570 		}
571 		setup_protocol(pr6, AF_INET6);
572 		outip6 = (*pr6->set_buffers_fn)(pr6->packlen);
573 		setup_socket(pr6, pr6->packlen);
574 		num_ifs6 = set_src_addr(pr6, &al6);
575 		break;
576 	case AF_INET:
577 		pr4 = (struct pr_set *)malloc(sizeof (struct pr_set));
578 		if (pr4 == NULL) {
579 			Fprintf(stderr,
580 			    "%s: malloc %s\n", prog, strerror(errno));
581 			exit(EXIT_FAILURE);
582 		}
583 		setup_protocol(pr4, AF_INET);
584 		outip4 = (*pr4->set_buffers_fn)(pr4->packlen);
585 		setup_socket(pr4, pr4->packlen);
586 		num_ifs4 = set_src_addr(pr4, &al4);
587 		break;
588 	default:
589 		Fprintf(stderr, "%s: unknow address family.\n", prog);
590 		exit(EXIT_FAILURE);
591 	}
592 
593 	if (num_v4 + num_v6 > 1 && !probe_all) {
594 		if (ai_dst->ai_family == AF_INET) {
595 			Fprintf(stderr,
596 			    "%s: Warning: %s has multiple addresses;"
597 			    " using %s\n", prog, hostname,
598 			    inet_ntop(AF_INET,
599 			    /* LINTED E_BAD_PTR_CAST_ALIGN */
600 			    (void *)&((struct sockaddr_in *)
601 			    ai_dst->ai_addr)->sin_addr,
602 			    temp_buf, sizeof (temp_buf)));
603 		} else {
604 			Fprintf(stderr,
605 			    "%s: Warning: %s has multiple addresses;"
606 			    " using %s\n", prog, hostname,
607 			    inet_ntop(AF_INET6,
608 			    /* LINTED E_BAD_PTR_CAST_ALIGN */
609 			    (void *)&((struct sockaddr_in6 *)
610 			    ai_dst->ai_addr)->sin6_addr,
611 			    temp_buf, sizeof (temp_buf)));
612 		}
613 	}
614 
615 	if (num_ifs4 + num_ifs6 > 0) {
616 		trace_it(ai_dst);
617 		probing_successful = _B_TRUE;
618 	}
619 
620 	(void) close(rcvsock4);
621 	(void) close(sndsock4);
622 	(void) close(rcvsock6);
623 	(void) close(sndsock6);
624 
625 	/*
626 	 * if we could probe any of the IP addresses of the target, that means
627 	 * this was a successful operation
628 	 */
629 	if (probing_successful)
630 		return (EXIT_SUCCESS);
631 	else
632 		return (EXIT_FAILURE);
633 }
634 
635 /*
636  * print "unknown host" message
637  */
638 static void
639 print_unknown_host_msg(const char *protocol, const char *host)
640 {
641 	Fprintf(stderr, "%s: unknown%s host %s\n", prog, protocol, host);
642 }
643 
644 /*
645  * resolve destination host and gateways
646  */
647 static void
648 resolve_nodes(int *family, struct addrinfo **ai_dstp)
649 {
650 	struct addrinfo *ai_dst = NULL;
651 	struct addrinfo *aip = NULL;
652 	int num_resolved_gw = 0;
653 	int num_resolved_gw6 = 0;
654 
655 	get_hostinfo(hostname, *family, &ai_dst);
656 	if (ai_dst == NULL) {
657 		print_unknown_host_msg("", hostname);
658 		exit(EXIT_FAILURE);
659 	}
660 	/* Get a count of the v4 & v6 addresses */
661 	for (aip = ai_dst; aip != NULL; aip = aip->ai_next) {
662 		switch (aip->ai_family) {
663 		case AF_INET:
664 			num_v4++;
665 			break;
666 		case AF_INET6:
667 			num_v6++;
668 			break;
669 		}
670 	}
671 
672 	if (*family == AF_UNSPEC && !probe_all) {
673 		*family = ai_dst->ai_family;
674 	}
675 
676 	/* resolve gateways */
677 	if (gw_count > 0) {
678 		get_gwaddrs(gwlist, *family, gwIPlist, gwIP6list,
679 		    &num_resolved_gw, &num_resolved_gw6);
680 
681 		/* we couldn't resolve a gateway as an IPv6 host */
682 		if (num_resolved_gw6 != gw_count && num_v6 != 0) {
683 			if (*family == AF_INET6 || *family == AF_UNSPEC)
684 				print_unknown_host_msg(" IPv6",
685 				    gwlist[num_resolved_gw6]);
686 			num_v6 = 0;
687 		}
688 
689 		/* we couldn't resolve a gateway as an IPv4 host */
690 		if (num_resolved_gw != gw_count && num_v4 != 0) {
691 			if (*family == AF_INET || *family == AF_UNSPEC)
692 				print_unknown_host_msg(" IPv4",
693 				    gwlist[num_resolved_gw]);
694 			num_v4 = 0;
695 		}
696 	}
697 
698 	*ai_dstp = (num_v4 + num_v6 > 0) ? ai_dst : NULL;
699 }
700 
701 /*
702  * Given IP address or hostname, return v4 and v6 hostinfo lists.
703  * Assumes that hostinfo ** ptrs are non-null.
704  */
705 static void
706 get_hostinfo(char *host, int family, struct addrinfo **aipp)
707 {
708 	struct addrinfo hints, *ai;
709 	struct in6_addr addr6;
710 	struct in_addr addr;
711 	char temp_buf[INET6_ADDRSTRLEN];	/* use for inet_ntop() */
712 	int rc;
713 
714 	/*
715 	 * Take care of v4-mapped addresses. It should run same as v4, after
716 	 * chopping off the prefix, leaving the IPv4 address
717 	 */
718 	if ((inet_pton(AF_INET6, host, &addr6) > 0) &&
719 	    IN6_IS_ADDR_V4MAPPED(&addr6)) {
720 		/* peel off the "mapping" stuff, leaving 32 bit IPv4 address */
721 		IN6_V4MAPPED_TO_INADDR(&addr6, &addr);
722 
723 		/* convert it back to a string */
724 		(void) inet_ntop(AF_INET, (void *)&addr, temp_buf,
725 		    sizeof (temp_buf));
726 
727 		/* now the host is an IPv4 address */
728 		(void) strcpy(host, temp_buf);
729 
730 		/*
731 		 * If it's a mapped address, we convert it into IPv4
732 		 * address because traceroute will send and receive IPv4
733 		 * packets for that address. Therefore, it's a failure case to
734 		 * ask get_hostinfo() to treat a mapped address as an IPv6
735 		 * address.
736 		 */
737 		if (family == AF_INET6) {
738 			return;
739 		}
740 	}
741 
742 	(void) memset(&hints, 0, sizeof (hints));
743 	hints.ai_family = family;
744 	hints.ai_flags = AI_ADDRCONFIG;
745 	rc = getaddrinfo(host, NULL, &hints, &ai);
746 	if (rc != 0) {
747 		if (rc != EAI_NONAME)
748 			Fprintf(stderr, "%s: getaddrinfo: %s\n", prog,
749 			    gai_strerror(rc));
750 		*aipp = NULL;
751 		return;
752 	}
753 	*aipp = ai;
754 }
755 
756 /*
757  * Calculate the packet length to be used, and check against the valid range.
758  * Returns -1 if range check fails.
759  */
760 static uint_t
761 calc_packetlen(int plen_input, struct pr_set *pr)
762 {
763 	int minpacket;			/* min ip packet size */
764 	int optlen;			/* length of ip options */
765 	int plen;
766 
767 	/*
768 	 * LBNL bug fixed: miscalculation of optlen
769 	 */
770 	if (gw_count > 0) {
771 		/*
772 		 * IPv4:
773 		 * ----
774 		 * 5 (NO OPs) + 3 (code, len, ptr) + gateways
775 		 * IP options field can hold up to 9 gateways. But the API
776 		 * allows you to specify only 8, because the last one is the
777 		 * destination host. When this packet is sent, on the wire
778 		 * you see one gateway replaced by 4 NO OPs. The other 1 NO
779 		 * OP is for alignment
780 		 *
781 		 * IPv6:
782 		 * ----
783 		 * Well, formula is different, but the result is same.
784 		 * 8 byte fixed part for Type 0 Routing header, followed by
785 		 * gateway addresses
786 		 */
787 		optlen = 8 + gw_count * pr->addr_len;
788 	} else {
789 		optlen = 0;
790 	}
791 
792 	/* take care of the packet length calculations and checks */
793 	minpacket = pr->ip_hdr_len + sizeof (struct outdata) + optlen;
794 	if (useicmp)
795 		minpacket += pr->icmp_minlen;	/* minimum ICMP header size */
796 	else
797 		minpacket += sizeof (struct udphdr);
798 	plen = plen_input;
799 	if (plen == 0) {
800 		plen = minpacket;		/* minimum sized packet */
801 	} else if (minpacket > plen || plen > IP_MAXPACKET) {
802 		Fprintf(stderr, "%s: %s packet size must be >= %d and <= %d\n",
803 		    prog, pr->name, minpacket, IP_MAXPACKET);
804 		return (0);
805 	}
806 
807 	return (plen);
808 }
809 
810 /*
811  * Sets the source address by resolving -i and -s arguments, or if -i and -s
812  * don't dictate any, it sets the pick_src to make sure traceroute uses the
813  * kernel's pick of the source address.
814  * Returns number of interfaces configured on the source host, 0 on error or
815  * there's no interface which is up amd not a loopback.
816  */
817 static int
818 set_src_addr(struct pr_set *pr, struct ifaddrlist **alp)
819 {
820 	union any_in_addr *ap;
821 	struct ifaddrlist *al = NULL;
822 	struct ifaddrlist *tmp1_al = NULL;
823 	struct ifaddrlist *tmp2_al = NULL;
824 	/* LINTED E_BAD_PTR_CAST_ALIGN */
825 	struct sockaddr_in *sin_from = (struct sockaddr_in *)pr->from;
826 	/* LINTED E_BAD_PTR_CAST_ALIGN */
827 	struct sockaddr_in6 *sin6_from = (struct sockaddr_in6 *)pr->from;
828 	struct addrinfo *aip;
829 	char errbuf[ERRBUFSIZE];
830 	char temp_buf[INET6_ADDRSTRLEN];	/* use for inet_ntop() */
831 	int num_ifs;				/* all the interfaces  */
832 	int num_src_ifs;			/* exclude loopback and down */
833 	int i;
834 
835 	source = source_input;
836 
837 	/* get the interface address list */
838 	num_ifs = ifaddrlist(&al, pr->family, errbuf);
839 	if (num_ifs < 0) {
840 		Fprintf(stderr, "%s: ifaddrlist: %s\n", prog, errbuf);
841 		exit(EXIT_FAILURE);
842 	}
843 
844 	num_src_ifs = 0;
845 	for (i = 0; i < num_ifs; i++) {
846 		if (!(al[i].flags & IFF_LOOPBACK) && (al[i].flags & IFF_UP))
847 			num_src_ifs++;
848 	}
849 
850 	if (num_src_ifs == 0) {
851 		Fprintf(stderr, "%s: can't find any %s network interfaces\n",
852 		    prog, pr->name);
853 		return (0);
854 	}
855 
856 	/* verify the device */
857 	if (device != NULL) {
858 		tmp1_al = find_device(al, num_ifs, device);
859 
860 		if (tmp1_al == NULL) {
861 			Fprintf(stderr, "%s: %s (index %d) is an invalid %s"
862 			    " interface\n", prog, device, if_index, pr->name);
863 			free(al);
864 			return (0);
865 		}
866 	}
867 
868 	/* verify the source address */
869 	if (source != NULL) {
870 		get_hostinfo(source, pr->family, &aip);
871 		if (aip == NULL) {
872 			Fprintf(stderr,
873 			    "%s: %s is an invalid %s source address\n",
874 			    prog, source, pr->name);
875 
876 			free(al);
877 			return (0);
878 		}
879 
880 		source = aip->ai_canonname;
881 		ap = (union any_in_addr *)
882 		    /* LINTED E_BAD_PTR_CAST_ALIGN */
883 		    &((struct sockaddr_in6 *)
884 		    aip->ai_addr)->sin6_addr;
885 
886 		/*
887 		 * LBNL bug fixed: used to accept any src address
888 		 */
889 		tmp2_al = find_ifaddr(al, num_ifs, ap, pr->family);
890 
891 		if (tmp2_al == NULL) {
892 			Fprintf(stderr,
893 			    "%s: %s is an invalid %s source address\n", prog,
894 			    inet_ntop(pr->family, (const void *)ap,
895 				temp_buf, sizeof (temp_buf)),
896 			    pr->name);
897 
898 			free(al);
899 			freeaddrinfo(aip);
900 			return (0);
901 		}
902 	}
903 
904 	pick_src = _B_FALSE;
905 
906 	if (source == NULL) {			/* no -s used */
907 		if (device == NULL) {		/* no -i used, no -s used */
908 			pick_src = _B_TRUE;
909 		} else {			/* -i used, no -s used */
910 			/*
911 			 * -i used, but not -s, and it's IPv4: set the source
912 			 * address to whatever the interface has configured on
913 			 * it.
914 			 */
915 			if (pr->family == AF_INET)
916 				set_sin(pr->from, &(tmp1_al->addr), pr->family);
917 			else
918 				pick_src = _B_TRUE;
919 		}
920 	} else {				/* -s used */
921 		if (device == NULL) {		/* no -i used, -s used */
922 			set_sin(pr->from, ap, pr->family);
923 
924 			if (aip->ai_next != NULL) {
925 				Fprintf(stderr,
926 				    "%s: Warning: %s has multiple "
927 				    "addresses; using %s\n",
928 				    prog, source,
929 				    inet_ntop(pr->family,
930 					(const void *)pr->from_sin_addr,
931 					temp_buf, sizeof (temp_buf)));
932 			}
933 		} else {			/* -i and -s used */
934 			/*
935 			 * Make sure the source specified matches the
936 			 * interface address. You only care about this for IPv4
937 			 * IPv6 can handle IF not matching src address
938 			 */
939 			if (pr->family == AF_INET) {
940 				if (!has_addr(aip, &tmp1_al->addr)) {
941 					Fprintf(stderr,
942 					    "%s: %s is not on interface %s\n",
943 					    prog, source, device);
944 					exit(EXIT_FAILURE);
945 				}
946 				/*
947 				 * make sure we use the one matching the
948 				 * interface's address
949 				 */
950 				*ap = tmp1_al->addr;
951 			}
952 
953 			set_sin(pr->from, ap, pr->family);
954 		}
955 	}
956 
957 	/*
958 	 * Binding at this point will set the source address to be used
959 	 * for both IPv4 (when raw IP datagrams are not required) and
960 	 * IPv6.  If the address being bound to is zero, then the kernel
961 	 * will end up choosing the source address when the datagram is
962 	 * sent.
963 	 *
964 	 * For raw IPv4 datagrams, the source address is initialized
965 	 * within traceroute() along with the outbound destination
966 	 * address.
967 	 */
968 	if (pr->family == AF_INET && !raw_req) {
969 		sin_from->sin_family = AF_INET;
970 		sin_from->sin_port = htons(ident);
971 		if (bind(sndsock4, (struct sockaddr *)pr->from,
972 			sizeof (struct sockaddr_in)) < 0) {
973 			Fprintf(stderr, "%s: bind: %s\n", prog,
974 			    strerror(errno));
975 			exit(EXIT_FAILURE);
976 		}
977 	} else if (pr->family == AF_INET6) {
978 		sin6_from->sin6_family = AF_INET6;
979 		sin6_from->sin6_port = htons(ident);
980 		if (bind(sndsock6, (struct sockaddr *)pr->from,
981 			sizeof (struct sockaddr_in6)) < 0) {
982 			Fprintf(stderr, "%s: bind: %s\n", prog,
983 			    strerror(errno));
984 			exit(EXIT_FAILURE);
985 		}
986 
987 		whereto6.sin6_flowinfo = htonl((class << 20) | flow);
988 	}
989 	*alp = al;
990 	return (num_ifs);
991 }
992 
993 /*
994  * Returns the complete ifaddrlist structure matching the desired interface
995  * address. Ignores interfaces which are either down or loopback.
996  */
997 static struct ifaddrlist *
998 find_ifaddr(struct ifaddrlist *al, int len, union any_in_addr *addr,
999     int family)
1000 {
1001 	struct ifaddrlist *tmp_al = al;
1002 	int i;
1003 	size_t addr_len = (family == AF_INET) ? sizeof (struct in_addr) :
1004 	    sizeof (struct in6_addr);
1005 
1006 	for (i = 0; i < len; i++, tmp_al++) {
1007 		if ((!(tmp_al->flags & IFF_LOOPBACK) &&
1008 		    (tmp_al->flags & IFF_UP)) &&
1009 		    (memcmp(&tmp_al->addr, addr, addr_len) == 0))
1010 			break;
1011 	}
1012 
1013 	if (i < len) {
1014 		return (tmp_al);
1015 	} else {
1016 		return (NULL);
1017 	}
1018 }
1019 
1020 /*
1021  * Returns the complete ifaddrlist structure matching the desired interface name
1022  * Ignores interfaces which are either down or loopback.
1023  */
1024 static struct ifaddrlist *
1025 find_device(struct ifaddrlist *al, int len, char *device)
1026 {
1027 	struct ifaddrlist *tmp_al = al;
1028 	int i;
1029 
1030 	for (i = 0; i < len; i++, tmp_al++) {
1031 		if ((!(tmp_al->flags & IFF_LOOPBACK) &&
1032 		    (tmp_al->flags & IFF_UP)) &&
1033 		    (strcmp(tmp_al->device, device) == 0))
1034 			break;
1035 	}
1036 
1037 	if (i < len) {
1038 		return (tmp_al);
1039 	} else {
1040 		return (NULL);
1041 	}
1042 }
1043 
1044 /*
1045  * returns _B_TRUE if given hostinfo contains the given address
1046  */
1047 static boolean_t
1048 has_addr(struct addrinfo *ai, union any_in_addr *addr)
1049 {
1050 	struct addrinfo *ai_tmp = NULL;
1051 	union any_in_addr *ap;
1052 
1053 	for (ai_tmp = ai; ai_tmp != NULL; ai_tmp = ai_tmp->ai_next) {
1054 		if (ai_tmp->ai_family == AF_INET6)
1055 			continue;
1056 		ap = (union any_in_addr *)
1057 		    /* LINTED E_BAD_PTR_CAST_ALIGN */
1058 		    &((struct sockaddr_in *)ai_tmp->ai_addr)->sin_addr;
1059 		if (memcmp(ap, addr, sizeof (struct in_addr)) == 0)
1060 			break;
1061 	}
1062 
1063 	if (ai_tmp != NULL) {
1064 		return (_B_TRUE);
1065 	} else {
1066 		return (_B_FALSE);
1067 	}
1068 }
1069 
1070 /*
1071  * Resolve the gateway names, splitting results into v4 and v6 lists.
1072  * Gateway addresses are added to the appropriate passed-in array; the
1073  * number of resolved gateways for each af is returned in resolved[6].
1074  * Assumes that passed-in arrays are large enough for MAX_GWS[6] addrs
1075  * and resolved[6] ptrs are non-null; ignores array and counter if the
1076  * address family param makes them irrelevant.
1077  */
1078 static void
1079 get_gwaddrs(char **gwlist, int family, union any_in_addr *gwIPlist,
1080     union any_in_addr *gwIPlist6, int *resolved, int *resolved6)
1081 {
1082 	int i;
1083 	boolean_t check_v4 = _B_TRUE, check_v6 = _B_TRUE;
1084 	struct addrinfo *ai = NULL;
1085 	struct addrinfo *aip = NULL;
1086 
1087 	*resolved = *resolved6 = 0;
1088 	switch (family) {
1089 	case AF_UNSPEC:
1090 		break;
1091 	case AF_INET:
1092 		check_v6 = _B_FALSE;
1093 		break;
1094 	case AF_INET6:
1095 		check_v4 = _B_FALSE;
1096 		break;
1097 	default:
1098 		return;
1099 	}
1100 
1101 	if (check_v4 && gw_count >= MAX_GWS) {
1102 		check_v4 = _B_FALSE;
1103 		Fprintf(stderr, "%s: too many IPv4 gateways\n", prog);
1104 		num_v4 = 0;
1105 	}
1106 	if (check_v6 && gw_count >= MAX_GWS6) {
1107 		check_v6 = _B_FALSE;
1108 		Fprintf(stderr, "%s: too many IPv6 gateways\n", prog);
1109 		num_v6 = 0;
1110 	}
1111 
1112 	for (i = 0; i < gw_count; i++) {
1113 		if (!check_v4 && !check_v6)
1114 			return;
1115 		get_hostinfo(gwlist[i], family, &ai);
1116 		if (ai == NULL)
1117 			return;
1118 		if (check_v4 && num_v4 != 0) {
1119 			check_v4 = _B_FALSE;
1120 			for (aip = ai; aip != NULL; aip = aip->ai_next) {
1121 				if (aip->ai_family == AF_INET) {
1122 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1123 					bcopy(&((struct sockaddr_in *)
1124 					    aip->ai_addr)->sin_addr,
1125 					    &gwIPlist[i].addr,
1126 					    aip->ai_addrlen);
1127 					(*resolved)++;
1128 					check_v4 = _B_TRUE;
1129 					break;
1130 				}
1131 			}
1132 		} else if (check_v4) {
1133 			check_v4 = _B_FALSE;
1134 		}
1135 		if (check_v6 && num_v6 != 0) {
1136 			check_v6 = _B_FALSE;
1137 			for (aip = ai; aip != NULL; aip = aip->ai_next) {
1138 				if (aip->ai_family == AF_INET6) {
1139 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1140 					bcopy(&((struct sockaddr_in6 *)
1141 					    aip->ai_addr)->sin6_addr,
1142 					    &gwIPlist6[i].addr6,
1143 					    aip->ai_addrlen);
1144 					(*resolved6)++;
1145 					check_v6 = _B_TRUE;
1146 					break;
1147 				}
1148 			}
1149 		} else if (check_v6) {
1150 			check_v6 = _B_FALSE;
1151 		}
1152 	}
1153 	freeaddrinfo(ai);
1154 }
1155 
1156 /*
1157  * set protocol specific values here
1158  */
1159 static void
1160 setup_protocol(struct pr_set *pr, int family)
1161 {
1162 	/*
1163 	 * Set the global variables for each AF. This is going to save us lots
1164 	 * of "if (family == AF_INET)... else .."
1165 	 */
1166 	pr->family = family;
1167 
1168 	if (family == AF_INET) {
1169 		if (!docksum) {
1170 			Fprintf(stderr,
1171 			    "%s: Warning: checksums disabled\n", prog);
1172 		}
1173 		(void) strcpy(pr->name, "IPv4");
1174 		(void) strcpy(pr->icmp, "icmp");
1175 		pr->icmp_minlen = ICMP_MINLEN;
1176 		pr->addr_len = sizeof (struct in_addr);
1177 		pr->ip_hdr_len = sizeof (struct ip);
1178 		pr->sock_size = sizeof (struct sockaddr_in);
1179 		pr->to = (struct sockaddr *)&whereto;
1180 		pr->from = (struct sockaddr *)&wherefrom;
1181 		pr->from_sin_addr = (void *)&wherefrom.sin_addr;
1182 		pr->gwIPlist = gwIPlist;
1183 		pr->set_buffers_fn = set_buffers;
1184 		pr->check_reply_fn = check_reply;
1185 		pr->print_icmp_other_fn = print_icmp_other;
1186 		pr->print_addr_fn = print_addr;
1187 		pr->packlen = calc_packetlen(packlen_input, pr);
1188 	} else {
1189 		(void) strcpy(pr->name, "IPv6");
1190 		(void) strcpy(pr->icmp, "ipv6-icmp");
1191 		pr->icmp_minlen = ICMP6_MINLEN;
1192 		pr->addr_len = sizeof (struct in6_addr);
1193 		pr->ip_hdr_len = sizeof (struct ip6_hdr);
1194 		pr->sock_size = sizeof (struct sockaddr_in6);
1195 		pr->to = (struct sockaddr *)&whereto6;
1196 		pr->from = (struct sockaddr *)&wherefrom6;
1197 		pr->from_sin_addr = (void *)&wherefrom6.sin6_addr;
1198 		pr->gwIPlist = gwIP6list;
1199 		pr->set_buffers_fn = set_buffers6;
1200 		pr->check_reply_fn = check_reply6;
1201 		pr->print_icmp_other_fn = print_icmp_other6;
1202 		pr->print_addr_fn = print_addr6;
1203 		pr->packlen = calc_packetlen(packlen_input, pr);
1204 	}
1205 	if (pr->packlen == 0)
1206 		exit(EXIT_FAILURE);
1207 }
1208 
1209 /*
1210  * setup the sockets for the given protocol's address family
1211  */
1212 static void
1213 setup_socket(struct pr_set *pr, int packet_len)
1214 {
1215 	int on = 1;
1216 	struct protoent *pe;
1217 	int type;
1218 	int proto;
1219 	int int_op;
1220 	int rsock;
1221 	int ssock;
1222 
1223 	if ((pe = getprotobyname(pr->icmp)) == NULL) {
1224 		Fprintf(stderr, "%s: unknown protocol %s\n", prog, pr->icmp);
1225 		exit(EXIT_FAILURE);
1226 	}
1227 
1228 	/* privilege bracketing */
1229 	(void) __priv_bracket(PRIV_ON);
1230 
1231 	if ((rsock = socket(pr->family, SOCK_RAW, pe->p_proto)) < 0) {
1232 		Fprintf(stderr, "%s: icmp socket: %s\n", prog, strerror(errno));
1233 		exit(EXIT_FAILURE);
1234 	}
1235 
1236 	if (options & SO_DEBUG) {
1237 		if (setsockopt(rsock, SOL_SOCKET, SO_DEBUG, (char *)&on,
1238 		    sizeof (on)) < 0) {
1239 			Fprintf(stderr, "%s: SO_DEBUG: %s\n", prog,
1240 			    strerror(errno));
1241 			exit(EXIT_FAILURE);
1242 		}
1243 	}
1244 	if (options & SO_DONTROUTE) {
1245 		if (setsockopt(rsock, SOL_SOCKET, SO_DONTROUTE, (char *)&on,
1246 		    sizeof (on)) < 0) {
1247 			Fprintf(stderr, "%s: SO_DONTROUTE: %s\n", prog,
1248 			    strerror(errno));
1249 			exit(EXIT_FAILURE);
1250 		}
1251 	}
1252 
1253 	if (pr->family == AF_INET6) {
1254 		/* Enable receipt of destination address info */
1255 		if (setsockopt(rsock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
1256 		    (char *)&on, sizeof (on)) < 0) {
1257 			Fprintf(stderr, "%s: IPV6_RECVPKTINFO: %s\n", prog,
1258 			    strerror(errno));
1259 			exit(EXIT_FAILURE);
1260 		}
1261 		/* Enable receipt of hoplimit info */
1262 		if (setsockopt(rsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
1263 		    (char *)&on, sizeof (on)) < 0) {
1264 			Fprintf(stderr, "%s: IPV6_RECVHOPLIMIT: %s\n", prog,
1265 			    strerror(errno));
1266 			exit(EXIT_FAILURE);
1267 		}
1268 
1269 	}
1270 
1271 	/*
1272 	 * Initialize the socket type and protocol based on the address
1273 	 * family, whether or not a raw IP socket is required (for IPv4)
1274 	 * or whether ICMP will be used instead of UDP.
1275 	 *
1276 	 * For historical reasons, the datagrams sent out by
1277 	 * traceroute(1M) do not have the "don't fragment" flag set.  For
1278 	 * this reason as well as the ability to set the Loose Source and
1279 	 * Record Route (LSRR) option, a raw IP socket will be used for
1280 	 * IPv4 when run in the global zone.  Otherwise, the actual
1281 	 * datagram that will be sent will be a regular UDP or ICMP echo
1282 	 * request packet.  However for convenience and for future options
1283 	 * when other IP header information may be specified using
1284 	 * traceroute, the buffer including the raw IP and UDP or ICMP
1285 	 * header is always filled in.  When the probe is actually sent,
1286 	 * the size of the request and the start of the packet is set
1287 	 * according to the type of datagram to send.
1288 	 */
1289 	if (pr->family == AF_INET && raw_req) {
1290 		type = SOCK_RAW;
1291 		proto = IPPROTO_RAW;
1292 	} else if (useicmp) {
1293 		type = SOCK_RAW;
1294 		if (pr->family == AF_INET)
1295 			proto = IPPROTO_ICMP;
1296 		else
1297 			proto = IPPROTO_ICMPV6;
1298 	} else {
1299 		type = SOCK_DGRAM;
1300 		proto = IPPROTO_UDP;
1301 	}
1302 	ssock = socket(pr->family, type, proto);
1303 
1304 	if (ssock < 0) {
1305 		if (proto == IPPROTO_RAW) {
1306 			Fprintf(stderr, "%s: raw socket: %s\n", prog,
1307 			    strerror(errno));
1308 		} else if (proto == IPPROTO_UDP) {
1309 			Fprintf(stderr, "%s: udp socket: %s\n", prog,
1310 			    strerror(errno));
1311 		} else {
1312 			Fprintf(stderr, "%s: icmp socket: %s\n", prog,
1313 			    strerror(errno));
1314 		}
1315 		exit(EXIT_FAILURE);
1316 	}
1317 
1318 	if (setsockopt(ssock, SOL_SOCKET, SO_SNDBUF, (char *)&packet_len,
1319 	    sizeof (packet_len)) < 0) {
1320 		Fprintf(stderr, "%s: SO_SNDBUF: %s\n", prog, strerror(errno));
1321 		exit(EXIT_FAILURE);
1322 	}
1323 
1324 	if (pr->family == AF_INET && raw_req) {
1325 		if (setsockopt(ssock, IPPROTO_IP, IP_HDRINCL, (char *)&on,
1326 		    sizeof (on)) < 0) {
1327 			Fprintf(stderr, "%s: IP_HDRINCL: %s\n", prog,
1328 			    strerror(errno));
1329 			exit(EXIT_FAILURE);
1330 		}
1331 	}
1332 
1333 	if (options & SO_DEBUG) {
1334 		if (setsockopt(ssock, SOL_SOCKET, SO_DEBUG, (char *)&on,
1335 		    sizeof (on)) < 0) {
1336 			Fprintf(stderr, "%s: SO_DEBUG: %s\n", prog,
1337 			    strerror(errno));
1338 			exit(EXIT_FAILURE);
1339 		}
1340 	}
1341 	if (options & SO_DONTROUTE) {
1342 		if (setsockopt(ssock, SOL_SOCKET, SO_DONTROUTE,
1343 		    (char *)&on, sizeof (on)) < 0) {
1344 			Fprintf(stderr, "%s: SO_DONTROUTE: %s\n", prog,
1345 			    strerror(errno));
1346 			exit(EXIT_FAILURE);
1347 		}
1348 	}
1349 
1350 	/*
1351 	 * If a raw IPv4 packet is going to be sent, the Type of Service
1352 	 * field in the packet will be initialized in set_buffers().
1353 	 * Otherwise, it is initialized here using the IPPROTO_IP level
1354 	 * socket option.
1355 	 */
1356 	if (settos && !raw_req) {
1357 		int_op = tos;
1358 		if (setsockopt(ssock, IPPROTO_IP, IP_TOS, (char *)&int_op,
1359 		    sizeof (int_op)) < 0) {
1360 			Fprintf(stderr, "%s: IP_TOS: %s\n", prog,
1361 			    strerror(errno));
1362 			exit(EXIT_FAILURE);
1363 		}
1364 	}
1365 	if (pr->family == AF_INET) {
1366 		rcvsock4 = rsock;
1367 		sndsock4 = ssock;
1368 	} else {
1369 		rcvsock6 = rsock;
1370 		sndsock6 = ssock;
1371 	}
1372 	/* Revert to non-privileged user after configuring sockets */
1373 	(void) __priv_bracket(PRIV_OFF);
1374 }
1375 
1376 /*
1377  * If we are "probing all", this function calls traceroute() for each IP address
1378  * of the target, otherwise calls only once. Returns _B_FALSE if traceroute()
1379  * fails.
1380  */
1381 static void
1382 trace_it(struct addrinfo *ai_dst)
1383 {
1384 	struct msghdr msg6;
1385 	int num_dst_IPaddrs;
1386 	struct addrinfo *aip;
1387 	int i;
1388 
1389 	if (!probe_all)
1390 		num_dst_IPaddrs = 1;
1391 	else
1392 		num_dst_IPaddrs = num_v4 + num_v6;
1393 
1394 	/*
1395 	 * Initialize the msg6 structure using the hoplimit for the first
1396 	 * probe packet, gateway addresses and the outgoing interface index.
1397 	 */
1398 	if (ai_dst->ai_family == AF_INET6 || (probe_all && num_v6)) {
1399 		msg6.msg_control = NULL;
1400 		msg6.msg_controllen = 0;
1401 		set_ancillary_data(&msg6, first_ttl, pr6->gwIPlist, gw_count,
1402 		    if_index);
1403 	}
1404 
1405 	/* run traceroute for all the IP addresses of the multihomed dest */
1406 	for (aip = ai_dst, i = 0; i < num_dst_IPaddrs && aip != NULL; i++) {
1407 		union any_in_addr *addrp;
1408 		if (aip->ai_family == AF_INET) {
1409 			addrp = (union any_in_addr *)
1410 			    /* LINTED E_BAD_PTR_CAST_ALIGN */
1411 			    &((struct sockaddr_in *)
1412 			    aip->ai_addr)->sin_addr;
1413 			set_sin((struct sockaddr *)pr4->to, addrp,
1414 			    aip->ai_family);
1415 			traceroute(addrp, &msg6, pr4, num_ifs4, al4);
1416 		} else {
1417 			addrp = (union any_in_addr *)
1418 			    /* LINTED E_BAD_PTR_CAST_ALIGN */
1419 			    &((struct sockaddr_in6 *)
1420 			    aip->ai_addr)->sin6_addr;
1421 			set_sin((struct sockaddr *)pr6->to, addrp,
1422 			    aip->ai_family);
1423 			traceroute(addrp, &msg6, pr6, num_ifs6, al6);
1424 		}
1425 		aip = aip->ai_next;
1426 		if (i < (num_dst_IPaddrs - 1))
1427 			(void) putchar('\n');
1428 	}
1429 }
1430 
1431 /*
1432  * set the IP address in a sockaddr struct
1433  */
1434 static void
1435 set_sin(struct sockaddr *sock, union any_in_addr *addr, int family)
1436 {
1437 	sock->sa_family = family;
1438 
1439 	if (family == AF_INET)
1440 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1441 		((struct sockaddr_in *)sock)->sin_addr = addr->addr;
1442 	else
1443 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1444 		((struct sockaddr_in6 *)sock)->sin6_addr = addr->addr6;
1445 }
1446 
1447 /*
1448  * returns the IF name on which the given IP address is configured
1449  */
1450 static char *
1451 device_name(struct ifaddrlist *al, int len, union any_in_addr *ip_addr,
1452     struct pr_set *pr)
1453 {
1454 	int i;
1455 	struct ifaddrlist *tmp_al;
1456 
1457 	tmp_al = al;
1458 
1459 	for (i = 0; i < len; i++, tmp_al++) {
1460 		if (memcmp(&tmp_al->addr, ip_addr, pr->addr_len) == 0) {
1461 			return (tmp_al->device);
1462 		}
1463 	}
1464 
1465 	return (NULL);
1466 }
1467 
1468 /*
1469  * Trace the route to the host with given IP address.
1470  */
1471 static void
1472 traceroute(union any_in_addr *ip_addr, struct msghdr *msg6, struct pr_set *pr,
1473     int num_ifs, struct ifaddrlist *al)
1474 {
1475 	int ttl;
1476 	int probe;
1477 	uchar_t type;				/* icmp type */
1478 	uchar_t code;				/* icmp code */
1479 	int reply;
1480 	int seq = 0;
1481 	char temp_buf[INET6_ADDRSTRLEN];	/* use for inet_ntop() */
1482 	int longjmp_return;			/* return value from longjump */
1483 	struct ip *ip = (struct ip *)packet;
1484 	boolean_t got_there = _B_FALSE;		/* we hit the destination */
1485 	static boolean_t first_pkt = _B_TRUE;
1486 	int hoplimit;				/* hoplimit for IPv6 packets */
1487 	struct in6_addr addr6;
1488 	int num_src_ifs;			/* excludes down and loopback */
1489 	struct msghdr in_msg;
1490 	struct iovec iov;
1491 	int *intp;
1492 	int sndsock;
1493 	int rcvsock;
1494 
1495 	msg6->msg_name = pr->to;
1496 	msg6->msg_namelen = sizeof (struct sockaddr_in6);
1497 	sndsock =  (pr->family == AF_INET) ? sndsock4 : sndsock6;
1498 	rcvsock =  (pr->family == AF_INET) ? rcvsock4 : rcvsock6;
1499 
1500 	/* carry out the source address selection */
1501 	if (pick_src) {
1502 		union any_in_addr src_addr;
1503 		char *dev_name;
1504 		int i;
1505 
1506 		/*
1507 		 * If there's a gateway, a routing header as a consequence, our
1508 		 * kernel picks the source address based on the first hop
1509 		 * address, rather than final destination address.
1510 		 */
1511 		if (gw_count > 0) {
1512 			(void) select_src_addr(pr->gwIPlist, &src_addr,
1513 			    pr->family);
1514 		} else {
1515 			(void) select_src_addr(ip_addr, &src_addr, pr->family);
1516 		}
1517 		set_sin(pr->from, &src_addr, pr->family);
1518 
1519 		/* filter out down and loopback interfaces */
1520 		num_src_ifs = 0;
1521 		for (i = 0; i < num_ifs; i++) {
1522 			if (!(al[i].flags & IFF_LOOPBACK) &&
1523 			    (al[i].flags & IFF_UP))
1524 				num_src_ifs++;
1525 		}
1526 
1527 		if (num_src_ifs > 1) {
1528 			dev_name = device_name(al, num_ifs, &src_addr, pr);
1529 			if (dev_name == NULL)
1530 				dev_name = "?";
1531 
1532 			Fprintf(stderr,
1533 			    "%s: Warning: Multiple interfaces found;"
1534 			    " using %s @ %s\n",
1535 			    prog, inet_ntop(pr->family,
1536 				(const void *)pr->from_sin_addr,
1537 				temp_buf, sizeof (temp_buf)),
1538 			    dev_name);
1539 		}
1540 	}
1541 
1542 	if (pr->family == AF_INET) {
1543 		outip4->ip_src = *(struct in_addr *)pr->from_sin_addr;
1544 		outip4->ip_dst = ip_addr->addr;
1545 	}
1546 
1547 	/*
1548 	 * If the hostname is an IPv6 literal address, let's not print it twice.
1549 	 */
1550 	if (pr->family == AF_INET6 &&
1551 	    inet_pton(AF_INET6, hostname, &addr6) > 0) {
1552 		Fprintf(stderr, "%s to %s", prog, hostname);
1553 	} else {
1554 		Fprintf(stderr, "%s to %s (%s)", prog, hostname,
1555 		    inet_ntop(pr->family, (const void *)ip_addr, temp_buf,
1556 			sizeof (temp_buf)));
1557 	}
1558 
1559 	if (source)
1560 		Fprintf(stderr, " from %s", source);
1561 	Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl,
1562 	    pr->packlen);
1563 	(void) fflush(stderr);
1564 
1565 	/*
1566 	 * Setup the source routing for IPv4. For IPv6, we did the required
1567 	 * setup in the caller function, trace_it(), because it's independent
1568 	 * from the IP address of target.
1569 	 */
1570 	if (pr->family == AF_INET && gw_count > 0)
1571 		set_IPv4opt_sourcerouting(sndsock, ip_addr, pr->gwIPlist);
1572 
1573 	if (probe_all) {
1574 		/* interrupt handler sig_handler() jumps back to here */
1575 		if ((longjmp_return = setjmp(env)) != 0) {
1576 			switch (longjmp_return) {
1577 			case SIGINT:
1578 				Printf("(skipping)\n");
1579 				return;
1580 			case SIGQUIT:
1581 				Printf("(exiting)\n");
1582 				exit(EXIT_SUCCESS);
1583 			default:	/* should never happen */
1584 				exit(EXIT_FAILURE);
1585 			}
1586 		}
1587 		(void) signal(SIGINT, sig_handler);
1588 	}
1589 
1590 	for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
1591 		union any_in_addr lastaddr;
1592 		int timeouts = 0;
1593 		double rtt;		/* for statistics */
1594 		int nreceived = 0;
1595 		double rttmin, rttmax;
1596 		double rttsum, rttssq;
1597 		int unreachable;
1598 
1599 		got_there = _B_FALSE;
1600 		unreachable = 0;
1601 
1602 		/*
1603 		 * The following line clears both IPv4 and IPv6 address stored
1604 		 * in the union.
1605 		 */
1606 		lastaddr.addr6 = in6addr_any;
1607 
1608 		if ((ttl == (first_ttl + 1)) && (options & SO_DONTROUTE)) {
1609 			Fprintf(stderr,
1610 			    "%s: host %s is not on a directly-attached"
1611 			    " network\n", prog, hostname);
1612 			break;
1613 		}
1614 
1615 		Printf("%2d ", ttl);
1616 		(void) fflush(stdout);
1617 
1618 		for (probe = 0; (probe < nprobes) && (timeouts < max_timeout);
1619 		    ++probe) {
1620 			int cc;
1621 			struct timeval t1, t2;
1622 
1623 			/*
1624 			 * Put a delay before sending this probe packet. Don't
1625 			 * delay it if it's the very first packet.
1626 			 */
1627 			if (!first_pkt) {
1628 				if (delay.tv_sec > 0)
1629 					(void) sleep((uint_t)delay.tv_sec);
1630 				if (delay.tv_usec > 0)
1631 					(void) usleep(delay.tv_usec);
1632 			} else {
1633 				first_pkt = _B_FALSE;
1634 			}
1635 
1636 			(void) gettimeofday(&t1, NULL);
1637 
1638 			if (pr->family == AF_INET) {
1639 				send_probe(sndsock, pr->to, outip4, seq, ttl,
1640 				    &t1, pr->packlen);
1641 			} else {
1642 				send_probe6(sndsock, msg6, outip6, seq, ttl,
1643 				    &t1, pr->packlen);
1644 			}
1645 
1646 			/* prepare msghdr for recvmsg() */
1647 			in_msg.msg_name = pr->from;
1648 			in_msg.msg_namelen = pr->sock_size;
1649 
1650 			iov.iov_base = (char *)packet;
1651 			iov.iov_len = sizeof (packet);
1652 
1653 			in_msg.msg_iov = &iov;
1654 			in_msg.msg_iovlen = 1;
1655 
1656 			in_msg.msg_control = ancillary_data;
1657 			in_msg.msg_controllen = sizeof (ancillary_data);
1658 
1659 			while ((cc = wait_for_reply(rcvsock, &in_msg,
1660 			    &t1)) != 0) {
1661 				(void) gettimeofday(&t2, NULL);
1662 
1663 				reply = (*pr->check_reply_fn) (&in_msg, cc, seq,
1664 				    &type, &code);
1665 
1666 				in_msg.msg_controllen =
1667 				    sizeof (ancillary_data);
1668 				/* Skip short packet */
1669 				if (reply == REPLY_SHORT_PKT) {
1670 					continue;
1671 				}
1672 
1673 				timeouts = 0;
1674 
1675 				/*
1676 				 * if reply comes from a different host, print
1677 				 * the hostname
1678 				 */
1679 				if (memcmp(pr->from_sin_addr, &lastaddr,
1680 				    pr->addr_len) != 0) {
1681 					(*pr->print_addr_fn) ((uchar_t *)packet,
1682 					    cc, pr->from);
1683 					/* store the address response */
1684 					(void) memcpy(&lastaddr,
1685 					    pr->from_sin_addr, pr->addr_len);
1686 				}
1687 
1688 				rtt = deltaT(&t1, &t2);
1689 				if (collect_stat) {
1690 					record_stats(rtt, &nreceived, &rttmin,
1691 					    &rttmax, &rttsum, &rttssq);
1692 				} else {
1693 					Printf("  %.3f ms", rtt);
1694 				}
1695 
1696 				if (pr->family == AF_INET6) {
1697 					intp =
1698 					    (int *)find_ancillary_data(&in_msg,
1699 						IPPROTO_IPV6, IPV6_HOPLIMIT);
1700 					if (intp == NULL) {
1701 						Fprintf(stderr,
1702 						    "%s: can't find "
1703 						    "IPV6_HOPLIMIT ancillary "
1704 						    "data\n", prog);
1705 						exit(EXIT_FAILURE);
1706 					}
1707 					hoplimit = *intp;
1708 				}
1709 
1710 				if (reply == REPLY_GOT_TARGET) {
1711 					got_there = _B_TRUE;
1712 
1713 					if (((pr->family == AF_INET) &&
1714 					    (ip->ip_ttl <= 1)) ||
1715 					    ((pr->family == AF_INET6) &&
1716 					    (hoplimit <= 1)))
1717 						Printf(" !");
1718 				}
1719 
1720 				if (!collect_stat && showttl) {
1721 					if (pr->family == AF_INET) {
1722 						Printf(" (ttl=%d)",
1723 						    (int)ip->ip_ttl);
1724 					} else if (hoplimit != -1) {
1725 						Printf(" (hop limit=%d)",
1726 						    hoplimit);
1727 					}
1728 				}
1729 
1730 				if (reply == REPLY_GOT_OTHER) {
1731 					if ((*pr->print_icmp_other_fn)
1732 					    (type, code)) {
1733 						unreachable++;
1734 					}
1735 				}
1736 
1737 				/* special case */
1738 				if (pr->family == AF_INET &&
1739 				    type == ICMP_UNREACH &&
1740 				    code == ICMP_UNREACH_PROTOCOL)
1741 					got_there = _B_TRUE;
1742 
1743 				break;
1744 			}
1745 
1746 			seq = (seq + 1) % (MAX_SEQ + 1);
1747 
1748 			if (cc == 0) {
1749 				Printf(" *");
1750 				timeouts++;
1751 			}
1752 
1753 			(void) fflush(stdout);
1754 		}
1755 
1756 		if (collect_stat) {
1757 			print_stats(probe, nreceived, rttmin, rttmax, rttsum,
1758 			    rttssq);
1759 		}
1760 
1761 		(void) putchar('\n');
1762 
1763 		/* either we hit the target or received too many unreachables */
1764 		if (got_there ||
1765 		    (unreachable > 0 && unreachable >= nprobes - 1))
1766 			break;
1767 	}
1768 
1769 	/* Ignore the SIGINT between traceroute() runs */
1770 	if (probe_all)
1771 		(void) signal(SIGINT, SIG_IGN);
1772 }
1773 
1774 /*
1775  * for a given destination address and address family, it finds out what
1776  * source address kernel is going to pick
1777  */
1778 static void
1779 select_src_addr(union any_in_addr *dst_addr, union any_in_addr *src_addr,
1780     int family)
1781 {
1782 	int tmp_fd;
1783 	struct sockaddr *sock;
1784 	struct sockaddr_in *sin;
1785 	struct sockaddr_in6 *sin6;
1786 	size_t sock_len;
1787 
1788 	sock = (struct sockaddr *)malloc(sizeof (struct sockaddr_in6));
1789 	if (sock == NULL) {
1790 		Fprintf(stderr, "%s: malloc %s\n", prog, strerror(errno));
1791 		exit(EXIT_FAILURE);
1792 	}
1793 	(void) bzero(sock, sizeof (struct sockaddr_in6));
1794 
1795 	if (family == AF_INET) {
1796 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1797 		sin = (struct sockaddr_in *)sock;
1798 		sin->sin_family = AF_INET;
1799 		sin->sin_addr = dst_addr->addr;
1800 		sin->sin_port = IPPORT_ECHO;	/* port shouldn't be 0 */
1801 		sock_len = sizeof (struct sockaddr_in);
1802 	} else {
1803 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1804 		sin6 = (struct sockaddr_in6 *)sock;
1805 		sin6->sin6_family = AF_INET6;
1806 		sin6->sin6_addr = dst_addr->addr6;
1807 		sin6->sin6_port = IPPORT_ECHO;	/* port shouldn't be 0 */
1808 		sock_len = sizeof (struct sockaddr_in6);
1809 	}
1810 
1811 	/* open a UDP socket */
1812 	if ((tmp_fd = socket(family, SOCK_DGRAM, 0)) < 0) {
1813 		Fprintf(stderr, "%s: udp socket: %s\n", prog,
1814 		    strerror(errno));
1815 		exit(EXIT_FAILURE);
1816 	}
1817 
1818 	/* connect it */
1819 	if (connect(tmp_fd, sock, sock_len) < 0) {
1820 		/*
1821 		 * If there's no route to the destination, this connect() call
1822 		 * fails. We just return all-zero (wildcard) as the source
1823 		 * address, so that user can get to see "no route to dest"
1824 		 * message, as it'll try to send the probe packet out and will
1825 		 * receive ICMP unreachable.
1826 		 */
1827 		if (family == AF_INET)
1828 			src_addr->addr.s_addr = INADDR_ANY;
1829 		else
1830 			src_addr->addr6 = in6addr_any;
1831 		free(sock);
1832 		return;
1833 	}
1834 
1835 	/* get the local sock info */
1836 	if (getsockname(tmp_fd, sock, &sock_len) < 0) {
1837 		Fprintf(stderr, "%s: getsockname: %s\n", prog,
1838 		    strerror(errno));
1839 		exit(EXIT_FAILURE);
1840 	}
1841 
1842 	if (family == AF_INET) {
1843 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1844 		sin = (struct sockaddr_in *)sock;
1845 		src_addr->addr = sin->sin_addr;
1846 	} else {
1847 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1848 		sin6 = (struct sockaddr_in6 *)sock;
1849 		src_addr->addr6 = sin6->sin6_addr;
1850 	}
1851 
1852 	free(sock);
1853 	(void) close(tmp_fd);
1854 }
1855 
1856 /*
1857  * Checksum routine for Internet Protocol family headers (C Version)
1858  */
1859 ushort_t
1860 in_cksum(ushort_t *addr, int len)
1861 {
1862 	int nleft = len;
1863 	ushort_t *w = addr;
1864 	ushort_t answer;
1865 	int sum = 0;
1866 
1867 	/*
1868 	 *  Our algorithm is simple, using a 32 bit accumulator (sum),
1869 	 *  we add sequential 16 bit words to it, and at the end, fold
1870 	 *  back all the carry bits from the top 16 bits into the lower
1871 	 *  16 bits.
1872 	 */
1873 	while (nleft > 1)  {
1874 		sum += *w++;
1875 		nleft -= 2;
1876 	}
1877 
1878 	/* mop up an odd byte, if necessary */
1879 	if (nleft == 1)
1880 		sum += *(uchar_t *)w;
1881 
1882 	/* add back carry outs from top 16 bits to low 16 bits */
1883 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
1884 	sum += (sum >> 16);			/* add carry */
1885 	answer = ~sum;				/* truncate to 16 bits */
1886 	return (answer);
1887 }
1888 
1889 /*
1890  * Wait until a reply arrives or timeout occurs. If packet arrived, read it
1891  * return the size of the packet read.
1892  */
1893 static int
1894 wait_for_reply(int sock, struct msghdr *msg, struct timeval *tp)
1895 {
1896 	fd_set fds;
1897 	struct timeval now, wait;
1898 	int cc = 0;
1899 	int result;
1900 
1901 	(void) FD_ZERO(&fds);
1902 	FD_SET(sock, &fds);
1903 
1904 	wait.tv_sec = tp->tv_sec + waittime;
1905 	wait.tv_usec = tp->tv_usec;
1906 	(void) gettimeofday(&now, NULL);
1907 	tv_sub(&wait, &now);
1908 
1909 	if (wait.tv_sec < 0 || wait.tv_usec < 0)
1910 		return (0);
1911 
1912 	result = select(sock + 1, &fds, (fd_set *)NULL, (fd_set *)NULL, &wait);
1913 
1914 	if (result == -1) {
1915 		if (errno != EINTR) {
1916 			Fprintf(stderr, "%s: select: %s\n", prog,
1917 			    strerror(errno));
1918 		}
1919 	} else if (result > 0)
1920 		cc = recvmsg(sock, msg, 0);
1921 
1922 	return (cc);
1923 }
1924 
1925 /*
1926  * Construct an Internet address representation. If the nflag has been supplied,
1927  * give numeric value, otherwise try for symbolic name.
1928  */
1929 char *
1930 inet_name(union any_in_addr *in, int family)
1931 {
1932 	char *cp;
1933 	static boolean_t first = _B_TRUE;
1934 	static char domain[NI_MAXHOST + 1];
1935 	static char line[NI_MAXHOST + 1];	/* assuming		*/
1936 				/* (NI_MAXHOST + 1) >= INET6_ADDRSTRLEN */
1937 	char hbuf[NI_MAXHOST];
1938 	socklen_t slen;
1939 	struct sockaddr_in sin;
1940 	struct sockaddr_in6 sin6;
1941 	struct sockaddr *sa;
1942 	int flags;
1943 
1944 	switch (family) {
1945 	case AF_INET:
1946 		slen = sizeof (struct sockaddr_in);
1947 		sin.sin_addr = in->addr;
1948 		sin.sin_port = 0;
1949 		sa = (struct sockaddr *)&sin;
1950 		break;
1951 	case AF_INET6:
1952 		slen = sizeof (struct sockaddr_in6);
1953 		sin6.sin6_addr = in->addr6;
1954 		sin6.sin6_port = 0;
1955 		sa = (struct sockaddr *)&sin6;
1956 		break;
1957 	deafult:
1958 		(void) snprintf(line, sizeof (line),
1959 		    "<invalid address family>");
1960 		return (line);
1961 	}
1962 	sa->sa_family = family;
1963 
1964 	if (first && !nflag) {
1965 		/* find out the domain name */
1966 		first = _B_FALSE;
1967 		if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
1968 		    (cp = strchr(domain, '.')) != NULL) {
1969 			(void) strncpy(domain, cp + 1, sizeof (domain) - 1);
1970 			domain[sizeof (domain) - 1] = '\0';
1971 		} else {
1972 			domain[0] = '\0';
1973 		}
1974 	}
1975 
1976 	flags = (nflag) ? NI_NUMERICHOST : NI_NAMEREQD;
1977 	if (getnameinfo(sa, slen, hbuf, sizeof (hbuf), NULL, 0, flags) != 0) {
1978 		if (inet_ntop(family, (const void *)&in->addr6,
1979 		    hbuf, sizeof (hbuf)) == NULL)
1980 			hbuf[0] = 0;
1981 	} else if (!nflag && (cp = strchr(hbuf, '.')) != NULL &&
1982 	    strcmp(cp + 1, domain) == 0) {
1983 		*cp = '\0';
1984 	}
1985 	(void) strlcpy(line, hbuf, sizeof (line));
1986 
1987 	return (line);
1988 }
1989 
1990 /*
1991  * return the difference (in msec) between two time values
1992  */
1993 static double
1994 deltaT(struct timeval *t1p, struct timeval *t2p)
1995 {
1996 	double dt;
1997 
1998 	dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
1999 	    (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
2000 	return (dt);
2001 }
2002 
2003 /*
2004  * Subtract 2 timeval structs:  out = out - in.
2005  * Out is assumed to be >= in.
2006  */
2007 static void
2008 tv_sub(struct timeval *out, struct timeval *in)
2009 {
2010 	if ((out->tv_usec -= in->tv_usec) < 0)   {
2011 		--out->tv_sec;
2012 		out->tv_usec += 1000000;
2013 	}
2014 	out->tv_sec -= in->tv_sec;
2015 }
2016 
2017 /*
2018  * record statistics
2019  */
2020 static void
2021 record_stats(double rtt, int *nreceived, double *rttmin, double *rttmax,
2022     double *rttsum, double *rttssq)
2023 {
2024 	if (*nreceived == 0) {
2025 		*rttmin = rtt;
2026 		*rttmax = rtt;
2027 		*rttsum = rtt;
2028 		*rttssq = rtt * rtt;
2029 	} else {
2030 		if (rtt < *rttmin)
2031 			*rttmin = rtt;
2032 
2033 		if (rtt > *rttmax)
2034 			*rttmax = rtt;
2035 
2036 		*rttsum += rtt;
2037 		*rttssq += rtt * rtt;
2038 	}
2039 
2040 	(*nreceived)++;
2041 }
2042 
2043 /*
2044  * display statistics
2045  */
2046 static void
2047 print_stats(int ntransmitted, int nreceived, double rttmin, double rttmax,
2048     double rttsum, double rttssq)
2049 {
2050 	double rttavg;			/* average round-trip time */
2051 	double rttstd;			/* rtt standard deviation */
2052 
2053 	if (ntransmitted > 0 && ntransmitted >= nreceived) {
2054 		int missed = ntransmitted - nreceived;
2055 		double loss = 100 * (double)missed / (double)ntransmitted;
2056 
2057 		if (nreceived > 0) {
2058 			rttavg = rttsum / nreceived;
2059 			rttstd = rttssq - (rttavg * rttsum);
2060 			rttstd = xsqrt(rttstd / nreceived);
2061 
2062 			Printf("  %.3f", rttmin);
2063 			Printf("/%.3f", rttavg);
2064 			Printf("/%.3f", rttmax);
2065 
2066 			Printf(" (%.3f) ms ", rttstd);
2067 		}
2068 
2069 		Printf(" %d/%d pkts", nreceived, ntransmitted);
2070 
2071 		if (nreceived == 0)
2072 			Printf(" (100%% loss)");
2073 		else
2074 			Printf(" (%.2g%% loss)", loss);
2075 	}
2076 }
2077 
2078 /*
2079  * square root function
2080  */
2081 double
2082 xsqrt(double y)
2083 {
2084 	double t, x;
2085 
2086 	if (y <= 0) {
2087 		return (0.0);
2088 	}
2089 
2090 	x = (y < 1.0) ? 1.0 : y;
2091 	do {
2092 		t = x;
2093 		x = (t + (y/t))/2.0;
2094 	} while (0 < x && x < t);
2095 
2096 	return (x);
2097 }
2098 
2099 /*
2100  * String to double with optional min and max.
2101  */
2102 static double
2103 str2dbl(const char *str, const char *what, double mi, double ma)
2104 {
2105 	double val;
2106 	char *ep;
2107 
2108 	errno = 0;
2109 
2110 	val = strtod(str, &ep);
2111 	if (errno != 0 || *ep != '\0') {
2112 		Fprintf(stderr, "%s: \"%s\" bad value for %s \n",
2113 		    prog, str, what);
2114 		exit(EXIT_FAILURE);
2115 	}
2116 	if (val < mi && mi >= 0) {
2117 		Fprintf(stderr, "%s: %s must be >= %f\n", prog, what, mi);
2118 		exit(EXIT_FAILURE);
2119 	}
2120 	if (val > ma && ma >= 0) {
2121 		Fprintf(stderr, "%s: %s must be <= %f\n", prog, what, ma);
2122 		exit(EXIT_FAILURE);
2123 	}
2124 	return (val);
2125 }
2126 
2127 /*
2128  * String to int with optional min and max. Handles decimal and hex.
2129  */
2130 static int
2131 str2int(const char *str, const char *what, int mi, int ma)
2132 {
2133 	const char *cp;
2134 	int val;
2135 	char *ep;
2136 
2137 	errno = 0;
2138 
2139 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
2140 		cp = str + 2;
2141 		val = (int)strtol(cp, &ep, 16);
2142 	} else {
2143 		val = (int)strtol(str, &ep, 10);
2144 	}
2145 	if (errno != 0 || *ep != '\0') {
2146 		Fprintf(stderr, "%s: \"%s\" bad value for %s \n",
2147 		    prog, str, what);
2148 		exit(EXIT_FAILURE);
2149 	}
2150 	if (val < mi && mi >= 0) {
2151 		if (mi == 0) {
2152 			Fprintf(stderr, "%s: %s must be >= %d\n",
2153 			    prog, what, mi);
2154 		} else {
2155 			Fprintf(stderr, "%s: %s must be > %d\n",
2156 			    prog, what, mi - 1);
2157 		}
2158 		exit(EXIT_FAILURE);
2159 	}
2160 	if (val > ma && ma >= 0) {
2161 		Fprintf(stderr, "%s: %s must be <= %d\n", prog, what, ma);
2162 		exit(EXIT_FAILURE);
2163 	}
2164 	return (val);
2165 }
2166 
2167 /*
2168  * This is the interrupt handler for SIGINT and SIGQUIT. It's completely handled
2169  * where it jumps to.
2170  */
2171 static void
2172 sig_handler(int sig)
2173 {
2174 	longjmp(env, sig);
2175 }
2176 
2177 /*
2178  * display the usage of traceroute
2179  */
2180 static void
2181 usage(void)
2182 {
2183 	Fprintf(stderr, "Usage: %s [-adFIlnSvx] [-A address_family] "
2184 "[-c traffic_class] \n"
2185 "\t[-f first_hop] [-g gateway [-g gateway ...]| -r] [-i iface]\n"
2186 "\t[-L flow_label] [-m max_hop] [-P pause_sec] [-p port] [-Q max_timeout]\n"
2187 "\t[-q nqueries] [-s src_addr] [-t tos] [-w wait_time] host [packetlen]\n",
2188 		prog);
2189 	exit(EXIT_FAILURE);
2190 }
2191