xref: /openbsd/usr.sbin/traceroute/traceroute.c (revision 771fbea0)
1 /*	$OpenBSD: traceroute.c,v 1.163 2020/02/11 18:41:39 deraadt 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 	/* Cannot pledge due to special setsockopt()s below */
331 	if (unveil("/", "r") == -1)
332 		err(1, "unveil");
333 	if (unveil(NULL, NULL) == -1)
334 		err(1, "unveil");
335 
336 	if ((conf = calloc(1, sizeof(*conf))) == NULL)
337 		err(1,NULL);
338 
339 	conf->incflag = 1;
340 	conf->first_ttl = 1;
341 	conf->proto = IPPROTO_UDP;
342 	conf->max_ttl = IPDEFTTL;
343 	conf->nprobes = 3;
344 
345 	/* start udp dest port # for probe packets */
346 	conf->port = 32768+666;
347 
348  	memset(&rcvmhdr, 0, sizeof(rcvmhdr));
349 	memset(&rcviov, 0, sizeof(rcviov));
350 
351 	rcvsock4 = rcvsock6 = sndsock4 = sndsock6 = -1;
352 	v4sock_errno = v6sock_errno = 0;
353 
354 	conf->waittime = 5 * 1000;
355 
356 	if ((rcvsock6 = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) == -1)
357 		v6sock_errno = errno;
358 	else if ((sndsock6 = socket(AF_INET6, SOCK_DGRAM, 0)) == -1)
359 		v6sock_errno = errno;
360 
361 	if ((rcvsock4 = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) == -1)
362 		v4sock_errno = errno;
363 	else if ((sndsock4 = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1)
364 		v4sock_errno = errno;
365 
366 	/* revoke privs */
367 	ouid = getuid();
368 	if (ouid == 0 && (pw = getpwnam(TRACEROUTE_USER)) != NULL) {
369 		uid = pw->pw_uid;
370 		gid = pw->pw_gid;
371 	} else {
372 		uid = getuid();
373 		gid = getgid();
374 	}
375 	if (ouid && (setgroups(1, &gid) ||
376 	    setresgid(gid, gid, gid) ||
377 	    setresuid(uid, uid, uid)))
378 		err(1, "unable to revoke privs");
379 
380 	if (strcmp("traceroute6", __progname) == 0) {
381 		v6flag = 1;
382 		if (v6sock_errno != 0)
383 			errc(5, v6sock_errno, rcvsock6 < 0 ? "socket(ICMPv6)" :
384 			    "socket(SOCK_DGRAM)");
385 		rcvsock = rcvsock6;
386 		sndsock = sndsock6;
387 		if (rcvsock4 >= 0)
388 			close(rcvsock4);
389 		if (sndsock4 >= 0)
390 			close(sndsock4);
391 	} else {
392 		if (v4sock_errno != 0)
393 			errc(5, v4sock_errno, rcvsock4 < 0 ? "icmp socket" :
394 			    "raw socket");
395 		rcvsock = rcvsock4;
396 		sndsock = sndsock4;
397 		if (rcvsock6 >= 0)
398 			close(rcvsock6);
399 		if (sndsock6 >= 0)
400 			close(sndsock6);
401 	}
402 
403 	if (v6flag) {
404 		mib[1] = PF_INET6;
405 		mib[2] = IPPROTO_IPV6;
406 		mib[3] = IPV6CTL_DEFHLIM;
407 		/* specify to tell receiving interface */
408 		if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on,
409 		    sizeof(on)) == -1)
410 			err(1, "setsockopt(IPV6_RECVPKTINFO)");
411 
412 		/* specify to tell hoplimit field of received IP6 hdr */
413 		if (setsockopt(rcvsock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &on,
414 		    sizeof(on)) == -1)
415 			err(1, "setsockopt(IPV6_RECVHOPLIMIT)");
416 	}
417 
418 	size = sizeof(i);
419 	if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), &i, &size, NULL, 0) == -1)
420 		err(1, "sysctl");
421 	conf->max_ttl = i;
422 
423 	while ((ch = getopt(argc, argv, v6flag ? "AcDdf:Ilm:np:q:Ss:t:w:vV:" :
424 	    "AcDdf:g:Ilm:nP:p:q:Ss:t:V:vw:x")) != -1)
425 		switch (ch) {
426 		case 'A':
427 			conf->Aflag = 1;
428 			break;
429 		case 'c':
430 			conf->incflag = 0;
431 			break;
432 		case 'd':
433 			conf->dflag = 1;
434 			break;
435 		case 'D':
436 			conf->dump = 1;
437 			break;
438 		case 'f':
439 			conf->first_ttl = strtonum(optarg, 1, conf->max_ttl,
440 			    &errstr);
441 			if (errstr)
442 				errx(1, "min ttl must be 1 to %u.",
443 				    conf->max_ttl);
444 			break;
445 		case 'g':
446 			if (conf->lsrr >= MAX_LSRR)
447 				errx(1, "too many gateways; max %d", MAX_LSRR);
448 			if (inet_aton(optarg, &conf->gateway[conf->lsrr]) ==
449 			    0) {
450 				hp = gethostbyname(optarg);
451 				if (hp == 0)
452 					errx(1, "unknown host %s", optarg);
453 				memcpy(&conf->gateway[conf->lsrr], hp->h_addr,
454 				    hp->h_length);
455 			}
456 			if (++conf->lsrr == 1)
457 				conf->lsrrlen = 4;
458 			conf->lsrrlen += 4;
459 			break;
460 		case 'I':
461 			if (conf->protoset)
462 				errx(1, "protocol already set with -P");
463 			conf->protoset = 1;
464 			conf->proto = IPPROTO_ICMP;
465 			break;
466 		case 'l':
467 			conf->ttl_flag = 1;
468 			break;
469 		case 'm':
470 			conf->max_ttl = strtonum(optarg, conf->first_ttl,
471 			    MAXTTL, &errstr);
472 			if (errstr)
473 				errx(1, "max ttl must be %u to %u.",
474 				    conf->first_ttl, MAXTTL);
475 			break;
476 		case 'n':
477 			conf->nflag = 1;
478 			break;
479 		case 'p':
480 			conf->port = strtonum(optarg, 1, 65535, &errstr);
481 			if (errstr)
482 				errx(1, "port must be >0, <65536.");
483 			break;
484 		case 'P':
485 			if (conf->protoset)
486 				errx(1, "protocol already set with -I");
487 			conf->protoset = 1;
488 			conf->proto = strtonum(optarg, 1, IPPROTO_MAX - 1,
489 			    &errstr);
490 			if (errstr) {
491 				struct protoent *pent;
492 
493 				pent = getprotobyname(optarg);
494 				if (pent)
495 					conf->proto = pent->p_proto;
496 				else
497 					errx(1, "proto must be >=1, or a "
498 					    "name.");
499 			}
500 			break;
501 		case 'q':
502 			conf->nprobes = strtonum(optarg, 1, INT_MAX, &errstr);
503 			if (errstr)
504 				errx(1, "nprobes must be >0.");
505 			break;
506 		case 's':
507 			/*
508 			 * set the ip source address of the outbound
509 			 * probe (e.g., on a multi-homed host).
510 			 */
511 			conf->source = optarg;
512 			break;
513 		case 'S':
514 			conf->sump = 1;
515 			break;
516 		case 't':
517 			if (!map_tos(optarg, &conf->tos)) {
518 				if (strlen(optarg) > 1 && optarg[0] == '0' &&
519 				    optarg[1] == 'x') {
520 					char *ep;
521 					errno = 0;
522 					ep = NULL;
523 					l = strtol(optarg, &ep, 16);
524 					if (errno || !*optarg || *ep ||
525 					    l < 0 || l > 255)
526 						errx(1, "illegal tos value %s",
527 						    optarg);
528 					conf->tos = (int)l;
529 				} else {
530 					conf->tos = strtonum(optarg, 0, 255,
531 					    &errstr);
532 					if (errstr)
533 						errx(1, "illegal tos value %s",
534 						    optarg);
535 				}
536 			}
537 			conf->tflag = 1;
538 			last_tos = conf->tos;
539 			break;
540 		case 'v':
541 			conf->verbose = 1;
542 			break;
543 		case 'V':
544 			conf->rtableid = (unsigned int)strtonum(optarg, 0,
545 			    RT_TABLEID_MAX, &errstr);
546 			if (errstr)
547 				errx(1, "rtable value is %s: %s",
548 				    errstr, optarg);
549 			if (setsockopt(sndsock, SOL_SOCKET, SO_RTABLE,
550 			    &conf->rtableid, sizeof(conf->rtableid)) == -1)
551 				err(1, "setsockopt SO_RTABLE");
552 			if (setsockopt(rcvsock, SOL_SOCKET, SO_RTABLE,
553 			    &conf->rtableid, sizeof(conf->rtableid)) == -1)
554 				err(1, "setsockopt SO_RTABLE");
555 			break;
556 		case 'w':
557 			conf->waittime = strtonum(optarg, 2, INT_MAX, &errstr);
558 			if (errstr)
559 				errx(1, "wait must be >1 sec.");
560 			conf->waittime *= 1000;
561 			break;
562 		case 'x':
563 			xflag = 1;
564 			break;
565 		default:
566 			usage(v6flag);
567 		}
568 
569 	if (ouid == 0 && (setgroups(1, &gid) ||
570 	    setresgid(gid, gid, gid) ||
571 	    setresuid(uid, uid, uid)))
572 		err(1, "unable to revoke privs");
573 
574 	argc -= optind;
575 	argv += optind;
576 
577 	if (argc < 1 || argc > 2)
578 		usage(v6flag);
579 
580 	setvbuf(stdout, NULL, _IOLBF, 0);
581 
582 	conf->ident = (getpid() & 0xffff) | 0x8000;
583 	tmprnd = arc4random();
584 	sec_perturb = (tmprnd & 0x80000000) ? -(tmprnd & 0x7ff) :
585 	    (tmprnd & 0x7ff);
586 	usec_perturb = arc4random();
587 
588 	memset(&to4, 0, sizeof(to4));
589 	memset(&to6, 0, sizeof(to6));
590 
591 	dest = *argv;
592 
593 	memset(&hints, 0, sizeof(hints));
594 	hints.ai_family = v6flag ? PF_INET6 : PF_INET;
595 	hints.ai_socktype = SOCK_RAW;
596 	hints.ai_protocol = 0;
597 	hints.ai_flags = AI_CANONNAME;
598 	if ((error = getaddrinfo(dest, NULL, &hints, &res)))
599 		errx(1, "%s", gai_strerror(error));
600 
601 	switch (res->ai_family) {
602 	case AF_INET:
603 		to = (struct sockaddr *)&to4;
604 		from = (struct sockaddr *)&from4;
605 		break;
606 	case AF_INET6:
607 		to = (struct sockaddr *)&to6;
608 		from = (struct sockaddr *)&from6;
609 		break;
610 	default:
611 		errx(1, "unsupported AF: %d", res->ai_family);
612 		break;
613 	}
614 
615 	memcpy(to, res->ai_addr, res->ai_addrlen);
616 
617 	if (!hostname) {
618 		hostname = res->ai_canonname ? strdup(res->ai_canonname) : dest;
619 		if (!hostname)
620 			errx(1, "malloc");
621 	}
622 
623 	if (res->ai_next) {
624 		if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
625 		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0)
626 			strlcpy(hbuf, "?", sizeof(hbuf));
627 		warnx("Warning: %s has multiple "
628 		    "addresses; using %s", hostname, hbuf);
629 	}
630 	freeaddrinfo(res);
631 
632 	if (*++argv) {
633 		datalen = strtonum(*argv, 0, INT_MAX, &errstr);
634 		if (errstr)
635 			errx(1, "datalen out of range");
636 	}
637 
638 	switch (to->sa_family) {
639 	case AF_INET:
640 		switch (conf->proto) {
641 		case IPPROTO_UDP:
642 			headerlen = (sizeof(struct ip) + conf->lsrrlen +
643 			    sizeof(struct udphdr) + sizeof(struct packetdata));
644 			break;
645 		case IPPROTO_ICMP:
646 			headerlen = (sizeof(struct ip) + conf->lsrrlen +
647 			    sizeof(struct icmp) + sizeof(struct packetdata));
648 			break;
649 		default:
650 			headerlen = (sizeof(struct ip) + conf->lsrrlen +
651 			    sizeof(struct packetdata));
652 		}
653 
654 		if (datalen < 0 || datalen > IP_MAXPACKET - headerlen)
655 			errx(1, "packet size must be 0 to %d.",
656 			    IP_MAXPACKET - headerlen);
657 
658 		datalen += headerlen;
659 
660 		if ((outpacket = calloc(1, datalen)) == NULL)
661 			err(1, "calloc");
662 
663 		rcviov[0].iov_base = (caddr_t)packet;
664 		rcviov[0].iov_len = sizeof(packet);
665 		rcvmhdr.msg_name = (caddr_t)&from4;
666 		rcvmhdr.msg_namelen = sizeof(from4);
667 		rcvmhdr.msg_iov = rcviov;
668 		rcvmhdr.msg_iovlen = 1;
669 		rcvmhdr.msg_control = NULL;
670 		rcvmhdr.msg_controllen = 0;
671 
672 		ip = (struct ip *)outpacket;
673 		if (conf->lsrr != 0) {
674 			u_char *p = (u_char *)(ip + 1);
675 
676 			*p++ = IPOPT_NOP;
677 			*p++ = IPOPT_LSRR;
678 			*p++ = conf->lsrrlen - 1;
679 			*p++ = IPOPT_MINOFF;
680 			conf->gateway[conf->lsrr] = to4.sin_addr;
681 			for (i = 1; i <= conf->lsrr; i++) {
682 				memcpy(p, &conf->gateway[i],
683 				    sizeof(struct in_addr));
684 				p += sizeof(struct in_addr);
685 			}
686 			ip->ip_dst = conf->gateway[0];
687 		} else
688 			ip->ip_dst = to4.sin_addr;
689 		ip->ip_off = htons(0);
690 		ip->ip_hl = (sizeof(struct ip) + conf->lsrrlen) >> 2;
691 		ip->ip_p = conf->proto;
692 		ip->ip_v = IPVERSION;
693 		ip->ip_tos = conf->tos;
694 
695 		if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL,
696 		     &on, sizeof(on)) == -1)
697 			err(6, "IP_HDRINCL");
698 
699 		if (conf->source) {
700 			memset(&from4, 0, sizeof(from4));
701 			from4.sin_family = AF_INET;
702 			if (inet_aton(conf->source, &from4.sin_addr) == 0)
703 				errx(1, "unknown host %s", conf->source);
704 			ip->ip_src = from4.sin_addr;
705 			if (ouid != 0 &&
706 			    (ntohl(from4.sin_addr.s_addr) & 0xff000000U) ==
707 			    0x7f000000U && (ntohl(to4.sin_addr.s_addr) &
708 			    0xff000000U) != 0x7f000000U)
709 				errx(1, "source is on 127/8, destination is"
710 				    " not");
711 			if (ouid && bind(sndsock, (struct sockaddr *)&from4,
712 			    sizeof(from4)) == -1)
713 				err(1, "bind");
714 		}
715 		packetlen = datalen;
716 		break;
717 	case AF_INET6:
718 		/*
719 		 * packetlen is the size of the complete IP packet sent and
720 		 * reported in the first line of output.
721 		 * For IPv4 this is equal to datalen since we are constructing
722 		 * a raw packet.
723 		 * For IPv6 we need to always add the size of the IP6 header
724 		 * and for UDP packets the size of the UDP header since they
725 		 * are prepended to the packet by the kernel
726 		 */
727 		packetlen = sizeof(struct ip6_hdr);
728 		switch (conf->proto) {
729 		case IPPROTO_UDP:
730 			headerlen = sizeof(struct packetdata);
731 			packetlen += sizeof(struct udphdr);
732 			break;
733 		case IPPROTO_ICMP:
734 			headerlen = sizeof(struct icmp6_hdr) +
735 			    sizeof(struct packetdata);
736 			break;
737 		default:
738 			errx(1, "Unsupported proto: %hhu", conf->proto);
739 			break;
740 		}
741 
742 		if (datalen < 0 || datalen > IP_MAXPACKET - headerlen)
743 			errx(1, "packet size must be 0 to %d.",
744 			    IP_MAXPACKET - headerlen);
745 
746 		datalen += headerlen;
747 		packetlen += datalen;
748 
749 		if ((outpacket = calloc(1, datalen)) == NULL)
750 			err(1, "calloc");
751 
752 		/* initialize msghdr for receiving packets */
753 		rcviov[0].iov_base = (caddr_t)packet;
754 		rcviov[0].iov_len = sizeof(packet);
755 		rcvmhdr.msg_name = (caddr_t)&from6;
756 		rcvmhdr.msg_namelen = sizeof(from6);
757 		rcvmhdr.msg_iov = rcviov;
758 		rcvmhdr.msg_iovlen = 1;
759 		rcvcmsglen = CMSG_SPACE(sizeof(struct in6_pktinfo)) +
760 		    CMSG_SPACE(sizeof(int));
761 
762 		if ((rcvcmsgbuf = malloc(rcvcmsglen)) == NULL)
763 			errx(1, "malloc");
764 		rcvmhdr.msg_control = (caddr_t) rcvcmsgbuf;
765 		rcvmhdr.msg_controllen = rcvcmsglen;
766 
767 		/*
768 		 * Send UDP or ICMP
769 		 */
770 		if (conf->proto == IPPROTO_ICMP) {
771 			close(sndsock);
772 			sndsock = rcvsock;
773 		}
774 
775 		/*
776 		 * Source selection
777 		 */
778 		memset(&from6, 0, sizeof(from6));
779 		if (conf->source) {
780 			memset(&hints, 0, sizeof(hints));
781 			hints.ai_family = AF_INET6;
782 			hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
783 			hints.ai_flags = AI_NUMERICHOST;
784 			if ((error = getaddrinfo(conf->source, "0", &hints,
785 			    &res)))
786 				errx(1, "%s: %s", conf->source,
787 				    gai_strerror(error));
788 			memcpy(&from6, res->ai_addr, res->ai_addrlen);
789 			freeaddrinfo(res);
790 		} else {
791 			struct sockaddr_in6 nxt;
792 			int dummy;
793 
794 			nxt = to6;
795 			nxt.sin6_port = htons(DUMMY_PORT);
796 			if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) == -1)
797 				err(1, "socket");
798 			if (conf->rtableid > 0 &&
799 			    setsockopt(dummy, SOL_SOCKET, SO_RTABLE,
800 			    &conf->rtableid, sizeof(conf->rtableid)) == -1)
801 				err(1, "setsockopt(SO_RTABLE)");
802 			if (connect(dummy, (struct sockaddr *)&nxt,
803 			    nxt.sin6_len) == -1)
804 				err(1, "connect");
805 			len = sizeof(from6);
806 			if (getsockname(dummy, (struct sockaddr *)&from6,
807 			    &len) == -1)
808 				err(1, "getsockname");
809 			close(dummy);
810 		}
811 
812 		from6.sin6_port = htons(0);
813 		if (bind(sndsock, (struct sockaddr *)&from6, from6.sin6_len) == -1)
814 			err(1, "bind sndsock");
815 
816 		if (conf->tflag) {
817 			if (setsockopt(sndsock, IPPROTO_IPV6, IPV6_TCLASS,
818 			    &conf->tos, sizeof(conf->tos)) == -1)
819 				err(6, "IPV6_TCLASS");
820 		}
821 
822 		len = sizeof(from6);
823 		if (getsockname(sndsock, (struct sockaddr *)&from6, &len) == -1)
824 			err(1, "getsockname");
825 		srcport = ntohs(from6.sin6_port);
826 		break;
827 	default:
828 		errx(1, "unsupported AF: %d", to->sa_family);
829 		break;
830 	}
831 
832 	if (conf->dflag) {
833 		(void) setsockopt(rcvsock, SOL_SOCKET, SO_DEBUG,
834 		    &on, sizeof(on));
835 		(void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
836 		    &on, sizeof(on));
837 	}
838 
839 	if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF,
840 	    &datalen, sizeof(datalen)) == -1)
841 		err(6, "SO_SNDBUF");
842 
843 	if (conf->nflag && !conf->Aflag) {
844 		if (pledge("stdio inet", NULL) == -1)
845 			err(1, "pledge");
846 	} else {
847 		if (pledge("stdio inet dns", NULL) == -1)
848 			err(1, "pledge");
849 	}
850 
851 	if (getnameinfo(to, to->sa_len, hbuf,
852 	    sizeof(hbuf), NULL, 0, NI_NUMERICHOST))
853 		strlcpy(hbuf, "(invalid)", sizeof(hbuf));
854 	fprintf(stderr, "%s to %s (%s)", __progname, hostname, hbuf);
855 	if (conf->source)
856 		fprintf(stderr, " from %s", conf->source);
857 	fprintf(stderr, ", %u hops max, %d byte packets\n", conf->max_ttl,
858 	    packetlen);
859 	(void) fflush(stderr);
860 
861 	if (conf->first_ttl > 1)
862 		printf("Skipping %u intermediate hops\n", conf->first_ttl - 1);
863 
864 	for (ttl = conf->first_ttl; ttl && ttl <= conf->max_ttl; ++ttl) {
865 		int got_there = 0, unreachable = 0, timeout = 0, loss;
866 		in_addr_t lastaddr = 0;
867 		struct in6_addr lastaddr6;
868 
869 		printf("%2u ", ttl);
870 		memset(&lastaddr6, 0, sizeof(lastaddr6));
871 		for (probe = 0, loss = 0; probe < conf->nprobes; ++probe) {
872 			int cc;
873 			struct timeval t1, t2;
874 
875 			gettime(&t1);
876 			send_probe(conf, ++seq, ttl, conf->incflag, to);
877 			curwaittime = conf->waittime;
878 			while ((cc = wait_for_reply(rcvsock, &rcvmhdr,
879 			    curwaittime))) {
880 				gettime(&t2);
881 				i = packet_ok(conf, to->sa_family, &rcvmhdr,
882 				    cc, seq, conf->incflag);
883 				/* Skip wrong packet */
884 				if (i == 0) {
885 					curwaittime = conf->waittime -
886 					    ((t2.tv_sec - t1.tv_sec) * 1000 +
887 					    (t2.tv_usec - t1.tv_usec) / 1000);
888 					if (curwaittime < 0)
889 						curwaittime = 0;
890 					continue;
891 				}
892 				if (to->sa_family == AF_INET) {
893 					ip = (struct ip *)packet;
894 					if (from4.sin_addr.s_addr != lastaddr) {
895 						print(conf, from,
896 						    cc - (ip->ip_hl << 2),
897 						    inet_ntop(AF_INET,
898 						    &ip->ip_dst, hbuf,
899 						    sizeof(hbuf)));
900 						lastaddr =
901 						    from4.sin_addr.s_addr;
902 					}
903 				} else if (to->sa_family == AF_INET6) {
904 					if (!IN6_ARE_ADDR_EQUAL(
905 					    &from6.sin6_addr, &lastaddr6)) {
906 						print(conf, from, cc,
907 						    rcvpktinfo ?
908 						    inet_ntop( AF_INET6,
909 						    &rcvpktinfo->ipi6_addr,
910 						    hbuf, sizeof(hbuf)) : "?");
911 						lastaddr6 = from6.sin6_addr;
912 					}
913 				} else
914 					errx(1, "unsupported AF: %d",
915 					    to->sa_family);
916 
917 				printf("  %g ms", deltaT(&t1, &t2));
918 				if (conf->ttl_flag)
919 					printf(" (%u)", v6flag ? rcvhlim :
920 					    ip->ip_ttl);
921 				if (to->sa_family == AF_INET) {
922 					if (i == -2) {
923 						if (ip->ip_ttl <= 1)
924 							printf(" !");
925 						++got_there;
926 						break;
927 					}
928 
929 					if (conf->tflag)
930 						check_tos(ip, &last_tos);
931 				}
932 
933 				/* time exceeded in transit */
934 				if (i == -1)
935 					break;
936 				icmp_code(to->sa_family, i - 1, &got_there,
937 				    &unreachable);
938 				break;
939 			}
940 			if (cc == 0) {
941 				printf(" *");
942 				timeout++;
943 				loss++;
944 			} else if (cc && probe == conf->nprobes - 1 &&
945 			    (xflag || conf->verbose))
946 				print_exthdr(packet, cc);
947 			(void) fflush(stdout);
948 		}
949 		if (conf->sump)
950 			printf(" (%d%% loss)", (loss * 100) / conf->nprobes);
951 		putchar('\n');
952 		if (got_there ||
953 		    (unreachable && (unreachable + timeout) >= conf->nprobes))
954 			break;
955 	}
956 	exit(0);
957 }
958 
959 void
960 usage(int v6flag)
961 {
962 	if (v6flag) {
963 		fprintf(stderr, "usage: %s "
964 		    "[-AcDdIlnSv] [-f first_hop] [-m max_hop] [-p port]\n"
965 		    "\t[-q nqueries] [-s sourceaddr] [-t toskeyword] [-V rtable] "
966 		    "[-w waittime]\n\thost [datalen]\n", __progname);
967 	} else {
968 		fprintf(stderr,
969 		    "usage: %s [-AcDdIlnSvx] [-f first_ttl] [-g gateway_addr] "
970 		    "[-m max_ttl]\n"
971 		    "\t[-P proto] [-p port] [-q nqueries] [-s sourceaddr]\n"
972 		    "\t[-t toskeyword] "
973 		    "[-V rtable] [-w waittime] host [datalen]\n",
974 		    __progname);
975 	}
976 	exit(1);
977 }
978