xref: /openbsd/usr.sbin/traceroute/traceroute.c (revision c255d9b6)
1 /*	$OpenBSD: traceroute.c,v 1.160 2019/03/19 23:27:50 tedu Exp $	*/
2 /*	$NetBSD: traceroute.c,v 1.10 1995/05/21 15:50:45 mycroft Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*-
34  * Copyright (c) 1990, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * This code is derived from software contributed to Berkeley by
38  * Van Jacobson.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  */
64 
65 /*
66  * traceroute host  - trace the route ip packets follow going to "host".
67  *
68  * Attempt to trace the route an ip packet would follow to some
69  * internet host.  We find out intermediate hops by launching probe
70  * packets with a small ttl (time to live) then listening for an
71  * icmp "time exceeded" reply from a gateway.  We start our probes
72  * with a ttl of one and increase by one until we get an icmp "port
73  * unreachable" (which means we got to "host") or hit a max (which
74  * defaults to 64 hops & can be changed with the -m flag).  Three
75  * probes (change with -q flag) are sent at each ttl setting and a
76  * line is printed showing the ttl, address of the gateway and
77  * round trip time of each probe.  If the probe answers come from
78  * different gateways, the address of each responding system will
79  * be printed.  If there is no response within a 5 sec. timeout
80  * interval (changed with the -w flag), a "*" is printed for that
81  * probe.
82  *
83  * Probe packets are UDP format.  We don't want the destination
84  * host to process them so the destination port is set to an
85  * unlikely value (if some clod on the destination is using that
86  * value, it can be changed with the -p flag).
87  *
88  * A sample use might be:
89  *
90  *     [yak 71]% traceroute nis.nsf.net.
91  *     traceroute to nis.nsf.net (35.1.1.48), 64 hops max, 56 byte packet
92  *      1  helios.ee.lbl.gov (128.3.112.1)  19 ms  19 ms  0 ms
93  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
94  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  39 ms  19 ms
95  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  39 ms
96  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  39 ms  39 ms  39 ms
97  *      6  128.32.197.4 (128.32.197.4)  40 ms  59 ms  59 ms
98  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  59 ms
99  *      8  129.140.70.13 (129.140.70.13)  99 ms  99 ms  80 ms
100  *      9  129.140.71.6 (129.140.71.6)  139 ms  239 ms  319 ms
101  *     10  129.140.81.7 (129.140.81.7)  220 ms  199 ms  199 ms
102  *     11  nic.merit.edu (35.1.1.48)  239 ms  239 ms  239 ms
103  *
104  * Note that lines 2 & 3 are the same.  This is due to a buggy
105  * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
106  * packets with a zero ttl.
107  *
108  * A more interesting example is:
109  *
110  *     [yak 72]% traceroute allspice.lcs.mit.edu.
111  *     traceroute to allspice.lcs.mit.edu (18.26.0.115), 64 hops max
112  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
113  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  19 ms  19 ms
114  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  19 ms
115  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  19 ms  39 ms  39 ms
116  *      5  ccn-nerif22.Berkeley.EDU (128.32.168.22)  20 ms  39 ms  39 ms
117  *      6  128.32.197.4 (128.32.197.4)  59 ms  119 ms  39 ms
118  *      7  131.119.2.5 (131.119.2.5)  59 ms  59 ms  39 ms
119  *      8  129.140.70.13 (129.140.70.13)  80 ms  79 ms  99 ms
120  *      9  129.140.71.6 (129.140.71.6)  139 ms  139 ms  159 ms
121  *     10  129.140.81.7 (129.140.81.7)  199 ms  180 ms  300 ms
122  *     11  129.140.72.17 (129.140.72.17)  300 ms  239 ms  239 ms
123  *     12  * * *
124  *     13  128.121.54.72 (128.121.54.72)  259 ms  499 ms  279 ms
125  *     14  * * *
126  *     15  * * *
127  *     16  * * *
128  *     17  * * *
129  *     18  ALLSPICE.LCS.MIT.EDU (18.26.0.115)  339 ms  279 ms  279 ms
130  *
131  * (I start to see why I'm having so much trouble with mail to
132  * MIT.)  Note that the gateways 12, 14, 15, 16 & 17 hops away
133  * either don't send ICMP "time exceeded" messages or send them
134  * with a ttl too small to reach us.  14 - 17 are running the
135  * MIT C Gateway code that doesn't send "time exceeded"s.  God
136  * only knows what's going on with 12.
137  *
138  * The silent gateway 12 in the above may be the result of a bug in
139  * the 4.[23]BSD network code (and its derivatives):  4.x (x <= 3)
140  * sends an unreachable message using whatever ttl remains in the
141  * original datagram.  Since, for gateways, the remaining ttl is
142  * zero, the icmp "time exceeded" is guaranteed to not make it back
143  * to us.  The behavior of this bug is slightly more interesting
144  * when it appears on the destination system:
145  *
146  *      1  helios.ee.lbl.gov (128.3.112.1)  0 ms  0 ms  0 ms
147  *      2  lilac-dmc.Berkeley.EDU (128.32.216.1)  39 ms  19 ms  39 ms
148  *      3  lilac-dmc.Berkeley.EDU (128.32.216.1)  19 ms  39 ms  19 ms
149  *      4  ccngw-ner-cc.Berkeley.EDU (128.32.136.23)  39 ms  40 ms  19 ms
150  *      5  ccn-nerif35.Berkeley.EDU (128.32.168.35)  39 ms  39 ms  39 ms
151  *      6  csgw.Berkeley.EDU (128.32.133.254)  39 ms  59 ms  39 ms
152  *      7  * * *
153  *      8  * * *
154  *      9  * * *
155  *     10  * * *
156  *     11  * * *
157  *     12  * * *
158  *     13  rip.Berkeley.EDU (128.32.131.22)  59 ms !  39 ms !  39 ms !
159  *
160  * Notice that there are 12 "gateways" (13 is the final
161  * destination) and exactly the last half of them are "missing".
162  * What's really happening is that rip (a Sun-3 running Sun OS3.5)
163  * is using the ttl from our arriving datagram as the ttl in its
164  * icmp reply.  So, the reply will time out on the return path
165  * (with no notice sent to anyone since icmp's aren't sent for
166  * icmp's) until we probe with a ttl that's at least twice the path
167  * length.  I.e., rip is really only 7 hops away.  A reply that
168  * returns with a ttl of 1 is a clue this problem exists.
169  * Traceroute prints a "!" after the time if the ttl is <= 1.
170  * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
171  * non-standard (HPUX) software, expect to see this problem
172  * frequently and/or take care picking the target host of your
173  * probes.
174  *
175  * Other possible annotations after the time are !H, !N, !P (got a host,
176  * network or protocol unreachable, respectively), !S or !F (source
177  * route failed or fragmentation needed -- neither of these should
178  * ever occur and the associated gateway is busted if you see one).  If
179  * almost all the probes result in some kind of unreachable, traceroute
180  * will give up and exit.
181  *
182  * Notes
183  * -----
184  * This program must be run by root or be setuid.  (I suggest that
185  * you *don't* make it setuid -- casual use could result in a lot
186  * of unnecessary traffic on our poor, congested nets.)
187  *
188  * This program requires a kernel mod that does not appear in any
189  * system available from Berkeley:  A raw ip socket using proto
190  * IPPROTO_RAW must interpret the data sent as an ip datagram (as
191  * opposed to data to be wrapped in a ip datagram).  See the README
192  * file that came with the source to this program for a description
193  * of the mods I made to /sys/netinet/raw_ip.c.  Your mileage may
194  * vary.  But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
195  * MODIFIED TO RUN THIS PROGRAM.
196  *
197  * The udp port usage may appear bizarre (well, ok, it is bizarre).
198  * The problem is that an icmp message only contains 8 bytes of
199  * data from the original datagram.  8 bytes is the size of a udp
200  * header so, if we want to associate replies with the original
201  * datagram, the necessary information must be encoded into the
202  * udp header (the ip id could be used but there's no way to
203  * interlock with the kernel's assignment of ip id's and, anyway,
204  * it would have taken a lot more kernel hacking to allow this
205  * code to set the ip id).  So, to allow two or more users to
206  * use traceroute simultaneously, we use this task's pid as the
207  * source port (the high bit is set to move the port number out
208  * of the "likely" range).  To keep track of which probe is being
209  * replied to (so times and/or hop counts don't get confused by a
210  * reply that was delayed in transit), we increment the destination
211  * port number before each probe.
212  *
213  * Don't use this as a coding example.  I was trying to find a
214  * routing problem and this code sort-of popped out after 48 hours
215  * without sleep.  I was amazed it ever compiled, much less ran.
216  *
217  * I stole the idea for this program from Steve Deering.  Since
218  * the first release, I've learned that had I attended the right
219  * IETF working group meetings, I also could have stolen it from Guy
220  * Almes or Matt Mathis.  I don't know (or care) who came up with
221  * the idea first.  I envy the originators' perspicacity and I'm
222  * glad they didn't keep the idea a secret.
223  *
224  * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
225  * enhancements to the original distribution.
226  *
227  * I've hacked up a round-trip-route version of this that works by
228  * sending a loose-source-routed udp datagram through the destination
229  * back to yourself.  Unfortunately, SO many gateways botch source
230  * routing, the thing is almost worthless.  Maybe one day...
231  *
232  *  -- Van Jacobson (van@helios.ee.lbl.gov)
233  *     Tue Dec 20 03:50:13 PST 1988
234  */
235 
236 
237 #include <arpa/inet.h>
238 #include <endian.h>
239 #include <err.h>
240 #include <errno.h>
241 #include <limits.h>
242 #include <netdb.h>
243 #include <netinet/icmp6.h>
244 #include <netinet/in.h>
245 #include <netinet/ip.h>
246 #include <netinet/ip6.h>
247 #include <netinet/ip_icmp.h>
248 #include <netinet/udp.h>
249 #include <pwd.h>
250 #include <stdio.h>
251 #include <stdlib.h>
252 #include <string.h>
253 #include <sys/socket.h>
254 #include <sys/sysctl.h>
255 #include <sys/time.h>
256 #include <sys/uio.h>
257 #include <unistd.h>
258 
259 #include "traceroute.h"
260 
261 int32_t	 sec_perturb;
262 int32_t	 usec_perturb;
263 
264 u_char	 packet[512];
265 u_char	*outpacket;	/* last inbound (icmp) packet */
266 
267 int	rcvsock;	/* receive (icmp) socket file descriptor */
268 int	sndsock;	/* send (udp) socket file descriptor */
269 
270 int	rcvhlim;
271 struct in6_pktinfo *rcvpktinfo;
272 
273 	int	datalen;	/* How much data */
274 
275 char	*hostname;
276 
277 u_int16_t	srcport;
278 
279 void	usage(int);
280 
281 #define	TRACEROUTE_USER	"_traceroute"
282 
283 int
284 main(int argc, char *argv[])
285 {
286 	int	mib[4] = { CTL_NET, PF_INET, IPPROTO_IP, IPCTL_DEFTTL };
287 	char	hbuf[NI_MAXHOST];
288 
289 	struct tr_conf		*conf;	/* configuration defaults */
290 	struct sockaddr_in	 from4, to4;
291 	struct sockaddr_in6	 from6, to6;
292 	struct sockaddr		*from, *to;
293 	struct addrinfo		 hints, *res;
294 	struct hostent		*hp;
295 	struct ip		*ip = NULL;
296 	struct iovec		 rcviov[2];
297 	struct msghdr		 rcvmhdr;
298 	static u_char		*rcvcmsgbuf;
299 	struct passwd		*pw;
300 
301 	long		 l;
302 	socklen_t	 len;
303 	size_t		 size;
304 
305 	int		 ch;
306 	int		 on = 1;
307 	int		 seq = 0;
308 	int		 error;
309 	int		 curwaittime;
310 	int		 headerlen;	/* How long packet's header is */
311 	int		 i;
312 	int		 last_tos = 0;
313 	int		 packetlen;
314 	int		 probe;
315 	int		 rcvcmsglen;
316 	int		 rcvsock4, rcvsock6;
317 	int		 sndsock4, sndsock6;
318 	u_int32_t	 tmprnd;
319 	int		 v4sock_errno, v6sock_errno;
320 	int		 v6flag = 0;
321 	int		 xflag = 0;	/* show ICMP extension header */
322 
323 	char		*dest;
324 	const char	*errstr;
325 	u_int8_t	 ttl;
326 
327 	uid_t		 ouid, uid;
328 	gid_t		 gid;
329 
330 	if ((conf = calloc(1, sizeof(*conf))) == NULL)
331 		err(1,NULL);
332 
333 	conf->incflag = 1;
334 	conf->first_ttl = 1;
335 	conf->proto = IPPROTO_UDP;
336 	conf->max_ttl = IPDEFTTL;
337 	conf->nprobes = 3;
338 
339 	/* start udp dest port # for probe packets */
340 	conf->port = 32768+666;
341 
342  	memset(&rcvmhdr, 0, sizeof(rcvmhdr));
343 	memset(&rcviov, 0, sizeof(rcviov));
344 
345 	rcvsock4 = rcvsock6 = sndsock4 = sndsock6 = -1;
346 	v4sock_errno = v6sock_errno = 0;
347 
348 	conf->waittime = 5 * 1000;
349 
350 	if ((rcvsock6 = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0)
351 		v6sock_errno = errno;
352 	else if ((sndsock6 = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
353 		v6sock_errno = errno;
354 
355 	if ((rcvsock4 = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0)
356 		v4sock_errno = errno;
357 	else if ((sndsock4 = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
358 		v4sock_errno = errno;
359 
360 	/* revoke privs */
361 	ouid = getuid();
362 	if (ouid == 0 && (pw = getpwnam(TRACEROUTE_USER)) != NULL) {
363 		uid = pw->pw_uid;
364 		gid = pw->pw_gid;
365 	} else {
366 		uid = getuid();
367 		gid = getgid();
368 	}
369 	if (ouid && (setgroups(1, &gid) ||
370 	    setresgid(gid, gid, gid) ||
371 	    setresuid(uid, uid, uid)))
372 		err(1, "unable to revoke privs");
373 
374 	if (strcmp("traceroute6", __progname) == 0) {
375 		v6flag = 1;
376 		if (v6sock_errno != 0)
377 			errc(5, v6sock_errno, rcvsock6 < 0 ? "socket(ICMPv6)" :
378 			    "socket(SOCK_DGRAM)");
379 		rcvsock = rcvsock6;
380 		sndsock = sndsock6;
381 		if (rcvsock4 >= 0)
382 			close(rcvsock4);
383 		if (sndsock4 >= 0)
384 			close(sndsock4);
385 	} else {
386 		if (v4sock_errno != 0)
387 			errc(5, v4sock_errno, rcvsock4 < 0 ? "icmp socket" :
388 			    "raw socket");
389 		rcvsock = rcvsock4;
390 		sndsock = sndsock4;
391 		if (rcvsock6 >= 0)
392 			close(rcvsock6);
393 		if (sndsock6 >= 0)
394 			close(sndsock6);
395 	}
396 
397 	if (v6flag) {
398 		mib[1] = PF_INET6;
399 		mib[2] = IPPROTO_IPV6;
400 		mib[3] = IPV6CTL_DEFHLIM;
401 		/* specify to tell receiving interface */
402 		if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
403 		    sizeof(on)) < 0)
404 			err(1, "setsockopt(IPV6_RECVPKTINFO)");
405 
406 		/* specify to tell hoplimit field of received IP6 hdr */
407 		if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
408 		    sizeof(on)) < 0)
409 			err(1, "setsockopt(IPV6_RECVHOPLIMIT)");
410 	}
411 
412 	size = sizeof(i);
413 	if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), &i, &size, NULL, 0) == -1)
414 		err(1, "sysctl");
415 	conf->max_ttl = i;
416 
417 	while ((ch = getopt(argc, argv, v6flag ? "AcDdf:Ilm:np:q:Ss:t:w:vV:" :
418 	    "AcDdf:g:Ilm:nP:p:q:Ss:t:V:vw:x")) != -1)
419 		switch (ch) {
420 		case 'A':
421 			conf->Aflag = 1;
422 			break;
423 		case 'c':
424 			conf->incflag = 0;
425 			break;
426 		case 'd':
427 			conf->dflag = 1;
428 			break;
429 		case 'D':
430 			conf->dump = 1;
431 			break;
432 		case 'f':
433 			conf->first_ttl = strtonum(optarg, 1, conf->max_ttl,
434 			    &errstr);
435 			if (errstr)
436 				errx(1, "min ttl must be 1 to %u.",
437 				    conf->max_ttl);
438 			break;
439 		case 'g':
440 			if (conf->lsrr >= MAX_LSRR)
441 				errx(1, "too many gateways; max %d", MAX_LSRR);
442 			if (inet_aton(optarg, &conf->gateway[conf->lsrr]) ==
443 			    0) {
444 				hp = gethostbyname(optarg);
445 				if (hp == 0)
446 					errx(1, "unknown host %s", optarg);
447 				memcpy(&conf->gateway[conf->lsrr], hp->h_addr,
448 				    hp->h_length);
449 			}
450 			if (++conf->lsrr == 1)
451 				conf->lsrrlen = 4;
452 			conf->lsrrlen += 4;
453 			break;
454 		case 'I':
455 			if (conf->protoset)
456 				errx(1, "protocol already set with -P");
457 			conf->protoset = 1;
458 			conf->proto = IPPROTO_ICMP;
459 			break;
460 		case 'l':
461 			conf->ttl_flag = 1;
462 			break;
463 		case 'm':
464 			conf->max_ttl = strtonum(optarg, conf->first_ttl,
465 			    MAXTTL, &errstr);
466 			if (errstr)
467 				errx(1, "max ttl must be %u to %u.",
468 				    conf->first_ttl, MAXTTL);
469 			break;
470 		case 'n':
471 			conf->nflag = 1;
472 			break;
473 		case 'p':
474 			conf->port = strtonum(optarg, 1, 65535, &errstr);
475 			if (errstr)
476 				errx(1, "port must be >0, <65536.");
477 			break;
478 		case 'P':
479 			if (conf->protoset)
480 				errx(1, "protocol already set with -I");
481 			conf->protoset = 1;
482 			conf->proto = strtonum(optarg, 1, IPPROTO_MAX - 1,
483 			    &errstr);
484 			if (errstr) {
485 				struct protoent *pent;
486 
487 				pent = getprotobyname(optarg);
488 				if (pent)
489 					conf->proto = pent->p_proto;
490 				else
491 					errx(1, "proto must be >=1, or a "
492 					    "name.");
493 			}
494 			break;
495 		case 'q':
496 			conf->nprobes = strtonum(optarg, 1, INT_MAX, &errstr);
497 			if (errstr)
498 				errx(1, "nprobes must be >0.");
499 			break;
500 		case 's':
501 			/*
502 			 * set the ip source address of the outbound
503 			 * probe (e.g., on a multi-homed host).
504 			 */
505 			conf->source = optarg;
506 			break;
507 		case 'S':
508 			conf->sump = 1;
509 			break;
510 		case 't':
511 			if (!map_tos(optarg, &conf->tos)) {
512 				if (strlen(optarg) > 1 && optarg[0] == '0' &&
513 				    optarg[1] == 'x') {
514 					char *ep;
515 					errno = 0;
516 					ep = NULL;
517 					l = strtol(optarg, &ep, 16);
518 					if (errno || !*optarg || *ep ||
519 					    l < 0 || l > 255)
520 						errx(1, "illegal tos value %s",
521 						    optarg);
522 					conf->tos = (int)l;
523 				} else {
524 					conf->tos = strtonum(optarg, 0, 255,
525 					    &errstr);
526 					if (errstr)
527 						errx(1, "illegal tos value %s",
528 						    optarg);
529 				}
530 			}
531 			conf->tflag = 1;
532 			last_tos = conf->tos;
533 			break;
534 		case 'v':
535 			conf->verbose = 1;
536 			break;
537 		case 'V':
538 			conf->rtableid = (unsigned int)strtonum(optarg, 0,
539 			    RT_TABLEID_MAX, &errstr);
540 			if (errstr)
541 				errx(1, "rtable value is %s: %s",
542 				    errstr, optarg);
543 			if (setsockopt(sndsock, SOL_SOCKET, SO_RTABLE,
544 			    &conf->rtableid, sizeof(conf->rtableid)) == -1)
545 				err(1, "setsockopt SO_RTABLE");
546 			if (setsockopt(rcvsock, SOL_SOCKET, SO_RTABLE,
547 			    &conf->rtableid, sizeof(conf->rtableid)) == -1)
548 				err(1, "setsockopt SO_RTABLE");
549 			break;
550 		case 'w':
551 			conf->waittime = strtonum(optarg, 2, INT_MAX, &errstr);
552 			if (errstr)
553 				errx(1, "wait must be >1 sec.");
554 			conf->waittime *= 1000;
555 			break;
556 		case 'x':
557 			xflag = 1;
558 			break;
559 		default:
560 			usage(v6flag);
561 		}
562 
563 	if (ouid == 0 && (setgroups(1, &gid) ||
564 	    setresgid(gid, gid, gid) ||
565 	    setresuid(uid, uid, uid)))
566 		err(1, "unable to revoke privs");
567 
568 	argc -= optind;
569 	argv += optind;
570 
571 	if (argc < 1 || argc > 2)
572 		usage(v6flag);
573 
574 	setvbuf(stdout, NULL, _IOLBF, 0);
575 
576 	conf->ident = (getpid() & 0xffff) | 0x8000;
577 	tmprnd = arc4random();
578 	sec_perturb = (tmprnd & 0x80000000) ? -(tmprnd & 0x7ff) :
579 	    (tmprnd & 0x7ff);
580 	usec_perturb = arc4random();
581 
582 	memset(&to4, 0, sizeof(to4));
583 	memset(&to6, 0, sizeof(to6));
584 
585 	dest = *argv;
586 
587 	memset(&hints, 0, sizeof(hints));
588 	hints.ai_family = v6flag ? PF_INET6 : PF_INET;
589 	hints.ai_socktype = SOCK_RAW;
590 	hints.ai_protocol = 0;
591 	hints.ai_flags = AI_CANONNAME;
592 	if ((error = getaddrinfo(dest, NULL, &hints, &res)))
593 		errx(1, "%s", gai_strerror(error));
594 
595 	switch (res->ai_family) {
596 	case AF_INET:
597 		to = (struct sockaddr *)&to4;
598 		from = (struct sockaddr *)&from4;
599 		break;
600 	case AF_INET6:
601 		to = (struct sockaddr *)&to6;
602 		from = (struct sockaddr *)&from6;
603 		break;
604 	default:
605 		errx(1, "unsupported AF: %d", res->ai_family);
606 		break;
607 	}
608 
609 	memcpy(to, res->ai_addr, res->ai_addrlen);
610 
611 	if (!hostname) {
612 		hostname = res->ai_canonname ? strdup(res->ai_canonname) : dest;
613 		if (!hostname)
614 			errx(1, "malloc");
615 	}
616 
617 	if (res->ai_next) {
618 		if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
619 		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
620 			strlcpy(hbuf, "?", sizeof(hbuf));
621 		warnx("Warning: %s has multiple "
622 		    "addresses; using %s", hostname, hbuf);
623 	}
624 	freeaddrinfo(res);
625 
626 	if (*++argv) {
627 		datalen = strtonum(*argv, 0, INT_MAX, &errstr);
628 		if (errstr)
629 			errx(1, "datalen out of range");
630 	}
631 
632 	switch (to->sa_family) {
633 	case AF_INET:
634 		switch (conf->proto) {
635 		case IPPROTO_UDP:
636 			headerlen = (sizeof(struct ip) + conf->lsrrlen +
637 			    sizeof(struct udphdr) + sizeof(struct packetdata));
638 			break;
639 		case IPPROTO_ICMP:
640 			headerlen = (sizeof(struct ip) + conf->lsrrlen +
641 			    sizeof(struct icmp) + sizeof(struct packetdata));
642 			break;
643 		default:
644 			headerlen = (sizeof(struct ip) + conf->lsrrlen +
645 			    sizeof(struct packetdata));
646 		}
647 
648 		if (datalen < 0 || datalen > IP_MAXPACKET - headerlen)
649 			errx(1, "packet size must be 0 to %d.",
650 			    IP_MAXPACKET - headerlen);
651 
652 		datalen += headerlen;
653 
654 		if ((outpacket = calloc(1, datalen)) == NULL)
655 			err(1, "calloc");
656 
657 		rcviov[0].iov_base = (caddr_t)packet;
658 		rcviov[0].iov_len = sizeof(packet);
659 		rcvmhdr.msg_name = (caddr_t)&from4;
660 		rcvmhdr.msg_namelen = sizeof(from4);
661 		rcvmhdr.msg_iov = rcviov;
662 		rcvmhdr.msg_iovlen = 1;
663 		rcvmhdr.msg_control = NULL;
664 		rcvmhdr.msg_controllen = 0;
665 
666 		ip = (struct ip *)outpacket;
667 		if (conf->lsrr != 0) {
668 			u_char *p = (u_char *)(ip + 1);
669 
670 			*p++ = IPOPT_NOP;
671 			*p++ = IPOPT_LSRR;
672 			*p++ = conf->lsrrlen - 1;
673 			*p++ = IPOPT_MINOFF;
674 			conf->gateway[conf->lsrr] = to4.sin_addr;
675 			for (i = 1; i <= conf->lsrr; i++) {
676 				memcpy(p, &conf->gateway[i],
677 				    sizeof(struct in_addr));
678 				p += sizeof(struct in_addr);
679 			}
680 			ip->ip_dst = conf->gateway[0];
681 		} else
682 			ip->ip_dst = to4.sin_addr;
683 		ip->ip_off = htons(0);
684 		ip->ip_hl = (sizeof(struct ip) + conf->lsrrlen) >> 2;
685 		ip->ip_p = conf->proto;
686 		ip->ip_v = IPVERSION;
687 		ip->ip_tos = conf->tos;
688 
689 		if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL,
690 		     &on, sizeof(on)) < 0)
691 			err(6, "IP_HDRINCL");
692 
693 		if (conf->source) {
694 			memset(&from4, 0, sizeof(from4));
695 			from4.sin_family = AF_INET;
696 			if (inet_aton(conf->source, &from4.sin_addr) == 0)
697 				errx(1, "unknown host %s", conf->source);
698 			ip->ip_src = from4.sin_addr;
699 			if (ouid != 0 &&
700 			    (ntohl(from4.sin_addr.s_addr) & 0xff000000U) ==
701 			    0x7f000000U && (ntohl(to4.sin_addr.s_addr) &
702 			    0xff000000U) != 0x7f000000U)
703 				errx(1, "source is on 127/8, destination is"
704 				    " not");
705 			if (ouid && bind(sndsock, (struct sockaddr *)&from4,
706 			    sizeof(from4)) < 0)
707 				err(1, "bind");
708 		}
709 		packetlen = datalen;
710 		break;
711 	case AF_INET6:
712 		/*
713 		 * packetlen is the size of the complete IP packet sent and
714 		 * reported in the first line of output.
715 		 * For IPv4 this is equal to datalen since we are constructing
716 		 * a raw packet.
717 		 * For IPv6 we need to always add the size of the IP6 header
718 		 * and for UDP packets the size of the UDP header since they
719 		 * are prepended to the packet by the kernel
720 		 */
721 		packetlen = sizeof(struct ip6_hdr);
722 		switch (conf->proto) {
723 		case IPPROTO_UDP:
724 			headerlen = sizeof(struct packetdata);
725 			packetlen += sizeof(struct udphdr);
726 			break;
727 		case IPPROTO_ICMP:
728 			headerlen = sizeof(struct icmp6_hdr) +
729 			    sizeof(struct packetdata);
730 			break;
731 		default:
732 			errx(1, "Unsupported proto: %hhu", conf->proto);
733 			break;
734 		}
735 
736 		if (datalen < 0 || datalen > IP_MAXPACKET - headerlen)
737 			errx(1, "packet size must be 0 to %d.",
738 			    IP_MAXPACKET - headerlen);
739 
740 		datalen += headerlen;
741 		packetlen += datalen;
742 
743 		if ((outpacket = calloc(1, datalen)) == NULL)
744 			err(1, "calloc");
745 
746 		/* initialize msghdr for receiving packets */
747 		rcviov[0].iov_base = (caddr_t)packet;
748 		rcviov[0].iov_len = sizeof(packet);
749 		rcvmhdr.msg_name = (caddr_t)&from6;
750 		rcvmhdr.msg_namelen = sizeof(from6);
751 		rcvmhdr.msg_iov = rcviov;
752 		rcvmhdr.msg_iovlen = 1;
753 		rcvcmsglen = CMSG_SPACE(sizeof(struct in6_pktinfo)) +
754 		    CMSG_SPACE(sizeof(int));
755 
756 		if ((rcvcmsgbuf = malloc(rcvcmsglen)) == NULL)
757 			errx(1, "malloc");
758 		rcvmhdr.msg_control = (caddr_t) rcvcmsgbuf;
759 		rcvmhdr.msg_controllen = rcvcmsglen;
760 
761 		/*
762 		 * Send UDP or ICMP
763 		 */
764 		if (conf->proto == IPPROTO_ICMP) {
765 			close(sndsock);
766 			sndsock = rcvsock;
767 		}
768 
769 		/*
770 		 * Source selection
771 		 */
772 		memset(&from6, 0, sizeof(from6));
773 		if (conf->source) {
774 			memset(&hints, 0, sizeof(hints));
775 			hints.ai_family = AF_INET6;
776 			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
777 			hints.ai_flags = AI_NUMERICHOST;
778 			if ((error = getaddrinfo(conf->source, "0", &hints,
779 			    &res)))
780 				errx(1, "%s: %s", conf->source,
781 				    gai_strerror(error));
782 			memcpy(&from6, res->ai_addr, res->ai_addrlen);
783 			freeaddrinfo(res);
784 		} else {
785 			struct sockaddr_in6 nxt;
786 			int dummy;
787 
788 			nxt = to6;
789 			nxt.sin6_port = htons(DUMMY_PORT);
790 			if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
791 				err(1, "socket");
792 			if (conf->rtableid > 0 &&
793 			    setsockopt(dummy, SOL_SOCKET, SO_RTABLE,
794 			    &conf->rtableid, sizeof(conf->rtableid)) < 0)
795 				err(1, "setsockopt(SO_RTABLE)");
796 			if (connect(dummy, (struct sockaddr *)&nxt,
797 			    nxt.sin6_len) < 0)
798 				err(1, "connect");
799 			len = sizeof(from6);
800 			if (getsockname(dummy, (struct sockaddr *)&from6,
801 			    &len) < 0)
802 				err(1, "getsockname");
803 			close(dummy);
804 		}
805 
806 		from6.sin6_port = htons(0);
807 		if (bind(sndsock, (struct sockaddr *)&from6, from6.sin6_len) <
808 		    0)
809 			err(1, "bind sndsock");
810 
811 		if (conf->tflag) {
812 			if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_TCLASS,
813 			    &conf->tos, sizeof(conf->tos)) < 0)
814 				err(6, "IPV6_TCLASS");
815 		}
816 
817 		len = sizeof(from6);
818 		if (getsockname(sndsock, (struct sockaddr *)&from6, &len) < 0)
819 			err(1, "getsockname");
820 		srcport = ntohs(from6.sin6_port);
821 		break;
822 	default:
823 		errx(1, "unsupported AF: %d", to->sa_family);
824 		break;
825 	}
826 
827 	if (conf->dflag) {
828 		(void) setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
829 		    &on, sizeof(on));
830 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
831 		    &on, sizeof(on));
832 	}
833 
834 	if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF,
835 	    &datalen, sizeof(datalen)) < 0)
836 		err(6, "SO_SNDBUF");
837 
838 	if (conf->nflag && !conf->Aflag) {
839 		if (pledge("stdio inet", NULL) == -1)
840 			err(1, "pledge");
841 	} else {
842 		if (pledge("stdio inet dns", NULL) == -1)
843 			err(1, "pledge");
844 	}
845 
846 	if (getnameinfo(to, to->sa_len, hbuf,
847 	    sizeof(hbuf), NULL, 0, NI_NUMERICHOST))
848 		strlcpy(hbuf, "(invalid)", sizeof(hbuf));
849 	fprintf(stderr, "%s to %s (%s)", __progname, hostname, hbuf);
850 	if (conf->source)
851 		fprintf(stderr, " from %s", conf->source);
852 	fprintf(stderr, ", %u hops max, %d byte packets\n", conf->max_ttl,
853 	    packetlen);
854 	(void) fflush(stderr);
855 
856 	if (conf->first_ttl > 1)
857 		printf("Skipping %u intermediate hops\n", conf->first_ttl - 1);
858 
859 	for (ttl = conf->first_ttl; ttl && ttl <= conf->max_ttl; ++ttl) {
860 		int got_there = 0, unreachable = 0, timeout = 0, loss;
861 		in_addr_t lastaddr = 0;
862 		struct in6_addr lastaddr6;
863 
864 		printf("%2u ", ttl);
865 		memset(&lastaddr6, 0, sizeof(lastaddr6));
866 		for (probe = 0, loss = 0; probe < conf->nprobes; ++probe) {
867 			int cc;
868 			struct timeval t1, t2;
869 
870 			gettime(&t1);
871 			send_probe(conf, ++seq, ttl, conf->incflag, to);
872 			curwaittime = conf->waittime;
873 			while ((cc = wait_for_reply(rcvsock, &rcvmhdr,
874 			    curwaittime))) {
875 				gettime(&t2);
876 				i = packet_ok(conf, to->sa_family, &rcvmhdr,
877 				    cc, seq, conf->incflag);
878 				/* Skip wrong packet */
879 				if (i == 0) {
880 					curwaittime = conf->waittime -
881 					    ((t2.tv_sec - t1.tv_sec) * 1000 +
882 					    (t2.tv_usec - t1.tv_usec) / 1000);
883 					if (curwaittime < 0)
884 						curwaittime = 0;
885 					continue;
886 				}
887 				if (to->sa_family == AF_INET) {
888 					ip = (struct ip *)packet;
889 					if (from4.sin_addr.s_addr != lastaddr) {
890 						print(conf, from,
891 						    cc - (ip->ip_hl << 2),
892 						    inet_ntop(AF_INET,
893 						    &ip->ip_dst, hbuf,
894 						    sizeof(hbuf)));
895 						lastaddr =
896 						    from4.sin_addr.s_addr;
897 					}
898 				} else if (to->sa_family == AF_INET6) {
899 					if (!IN6_ARE_ADDR_EQUAL(
900 					    &from6.sin6_addr, &lastaddr6)) {
901 						print(conf, from, cc,
902 						    rcvpktinfo ?
903 						    inet_ntop( AF_INET6,
904 						    &rcvpktinfo->ipi6_addr,
905 						    hbuf, sizeof(hbuf)) : "?");
906 						lastaddr6 = from6.sin6_addr;
907 					}
908 				} else
909 					errx(1, "unsupported AF: %d",
910 					    to->sa_family);
911 
912 				printf("  %g ms", deltaT(&t1, &t2));
913 				if (conf->ttl_flag)
914 					printf(" (%u)", v6flag ? rcvhlim :
915 					    ip->ip_ttl);
916 				if (to->sa_family == AF_INET) {
917 					if (i == -2) {
918 						if (ip->ip_ttl <= 1)
919 							printf(" !");
920 						++got_there;
921 						break;
922 					}
923 
924 					if (conf->tflag)
925 						check_tos(ip, &last_tos);
926 				}
927 
928 				/* time exceeded in transit */
929 				if (i == -1)
930 					break;
931 				icmp_code(to->sa_family, i - 1, &got_there,
932 				    &unreachable);
933 				break;
934 			}
935 			if (cc == 0) {
936 				printf(" *");
937 				timeout++;
938 				loss++;
939 			} else if (cc && probe == conf->nprobes - 1 &&
940 			    (xflag || conf->verbose))
941 				print_exthdr(packet, cc);
942 			(void) fflush(stdout);
943 		}
944 		if (conf->sump)
945 			printf(" (%d%% loss)", (loss * 100) / conf->nprobes);
946 		putchar('\n');
947 		if (got_there ||
948 		    (unreachable && (unreachable + timeout) >= conf->nprobes))
949 			break;
950 	}
951 	exit(0);
952 }
953 
954 void
955 usage(int v6flag)
956 {
957 	if (v6flag) {
958 		fprintf(stderr, "usage: %s "
959 		    "[-AcDdIlnSv] [-f first_hop] [-m max_hop] [-p port]\n"
960 		    "\t[-q nqueries] [-s src_addr] [-t toskeyword] [-V rtable] "
961 		    "[-w waittime]\n\thost [datalen]\n", __progname);
962 	} else {
963 		fprintf(stderr,
964 		    "usage: %s [-AcDdIlnSvx] [-f first_ttl] [-g gateway_addr] "
965 		    "[-m max_ttl]\n"
966 		    "\t[-P proto] [-p port] [-q nqueries] [-s src_addr]\n"
967 		    "\t[-t toskeyword] "
968 		    "[-V rtable] [-w waittime] host [datalen]\n",
969 		    __progname);
970 	}
971 	exit(1);
972 }
973