1 /*
2 * Copyright (c) 1988, 1989, 1991, 1994, 1995, 1996, 1997, 1998, 1999, 2000
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
16 * written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 */
21
22 /*
23 * traceroute host - trace the route ip packets follow going to "host".
24 *
25 * Attempt to trace the route an ip packet would follow to some
26 * internet host. We find out intermediate hops by launching probe
27 * packets with a small ttl (time to live) then listening for an
28 * icmp "time exceeded" reply from a gateway. We start our probes
29 * with a ttl of one and increase by one until we get an icmp "port
30 * unreachable" (which means we got to "host") or hit a max (which
31 * defaults to net.inet.ip.ttl hops & can be changed with the -m flag).
32 * Three probes (change with -q flag) are sent at each ttl setting and
33 * a line is printed showing the ttl, address of the gateway and
34 * round trip time of each probe. If the probe answers come from
35 * different gateways, the address of each responding system will
36 * be printed. If there is no response within a 5 sec. timeout
37 * interval (changed with the -w flag), a "*" is printed for that
38 * probe.
39 *
40 * Probe packets are UDP format. We don't want the destination
41 * host to process them so the destination port is set to an
42 * unlikely value (if some clod on the destination is using that
43 * value, it can be changed with the -p flag).
44 *
45 * A sample use might be:
46 *
47 * [yak 71]% traceroute nis.nsf.net.
48 * traceroute to nis.nsf.net (35.1.1.48), 64 hops max, 40 byte packets
49 * 1 helios.ee.lbl.gov (128.3.112.1) 19 ms 19 ms 0 ms
50 * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
51 * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
52 * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 39 ms
53 * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 39 ms 39 ms 39 ms
54 * 6 128.32.197.4 (128.32.197.4) 40 ms 59 ms 59 ms
55 * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 59 ms
56 * 8 129.140.70.13 (129.140.70.13) 99 ms 99 ms 80 ms
57 * 9 129.140.71.6 (129.140.71.6) 139 ms 239 ms 319 ms
58 * 10 129.140.81.7 (129.140.81.7) 220 ms 199 ms 199 ms
59 * 11 nic.merit.edu (35.1.1.48) 239 ms 239 ms 239 ms
60 *
61 * Note that lines 2 & 3 are the same. This is due to a buggy
62 * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
63 * packets with a zero ttl.
64 *
65 * A more interesting example is:
66 *
67 * [yak 72]% traceroute allspice.lcs.mit.edu.
68 * traceroute to allspice.lcs.mit.edu (18.26.0.115), 64 hops max, 40 byte packets
69 * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
70 * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 19 ms 19 ms
71 * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 19 ms
72 * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 19 ms 39 ms 39 ms
73 * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 20 ms 39 ms 39 ms
74 * 6 128.32.197.4 (128.32.197.4) 59 ms 119 ms 39 ms
75 * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 39 ms
76 * 8 129.140.70.13 (129.140.70.13) 80 ms 79 ms 99 ms
77 * 9 129.140.71.6 (129.140.71.6) 139 ms 139 ms 159 ms
78 * 10 129.140.81.7 (129.140.81.7) 199 ms 180 ms 300 ms
79 * 11 129.140.72.17 (129.140.72.17) 300 ms 239 ms 239 ms
80 * 12 * * *
81 * 13 128.121.54.72 (128.121.54.72) 259 ms 499 ms 279 ms
82 * 14 * * *
83 * 15 * * *
84 * 16 * * *
85 * 17 * * *
86 * 18 ALLSPICE.LCS.MIT.EDU (18.26.0.115) 339 ms 279 ms 279 ms
87 *
88 * (I start to see why I'm having so much trouble with mail to
89 * MIT.) Note that the gateways 12, 14, 15, 16 & 17 hops away
90 * either don't send ICMP "time exceeded" messages or send them
91 * with a ttl too small to reach us. 14 - 17 are running the
92 * MIT C Gateway code that doesn't send "time exceeded"s. God
93 * only knows what's going on with 12.
94 *
95 * The silent gateway 12 in the above may be the result of a bug in
96 * the 4.[23]BSD network code (and its derivatives): 4.x (x <= 3)
97 * sends an unreachable message using whatever ttl remains in the
98 * original datagram. Since, for gateways, the remaining ttl is
99 * zero, the icmp "time exceeded" is guaranteed to not make it back
100 * to us. The behavior of this bug is slightly more interesting
101 * when it appears on the destination system:
102 *
103 * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
104 * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 39 ms
105 * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 39 ms 19 ms
106 * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 19 ms
107 * 5 ccn-nerif35.Berkeley.EDU (128.32.168.35) 39 ms 39 ms 39 ms
108 * 6 csgw.Berkeley.EDU (128.32.133.254) 39 ms 59 ms 39 ms
109 * 7 * * *
110 * 8 * * *
111 * 9 * * *
112 * 10 * * *
113 * 11 * * *
114 * 12 * * *
115 * 13 rip.Berkeley.EDU (128.32.131.22) 59 ms ! 39 ms ! 39 ms !
116 *
117 * Notice that there are 12 "gateways" (13 is the final
118 * destination) and exactly the last half of them are "missing".
119 * What's really happening is that rip (a Sun-3 running Sun OS3.5)
120 * is using the ttl from our arriving datagram as the ttl in its
121 * icmp reply. So, the reply will time out on the return path
122 * (with no notice sent to anyone since icmp's aren't sent for
123 * icmp's) until we probe with a ttl that's at least twice the path
124 * length. I.e., rip is really only 7 hops away. A reply that
125 * returns with a ttl of 1 is a clue this problem exists.
126 * Traceroute prints a "!" after the time if the ttl is <= 1.
127 * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
128 * non-standard (HPUX) software, expect to see this problem
129 * frequently and/or take care picking the target host of your
130 * probes.
131 *
132 * Other possible annotations after the time are !H, !N, !P (got a host,
133 * network or protocol unreachable, respectively), !S or !F (source
134 * route failed or fragmentation needed -- neither of these should
135 * ever occur and the associated gateway is busted if you see one). If
136 * almost all the probes result in some kind of unreachable, traceroute
137 * will give up and exit.
138 *
139 * Notes
140 * -----
141 * This program must be run by root or be setuid. (I suggest that
142 * you *don't* make it setuid -- casual use could result in a lot
143 * of unnecessary traffic on our poor, congested nets.)
144 *
145 * This program requires a kernel mod that does not appear in any
146 * system available from Berkeley: A raw ip socket using proto
147 * IPPROTO_RAW must interpret the data sent as an ip datagram (as
148 * opposed to data to be wrapped in an ip datagram). See the README
149 * file that came with the source to this program for a description
150 * of the mods I made to /sys/netinet/raw_ip.c. Your mileage may
151 * vary. But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
152 * MODIFIED TO RUN THIS PROGRAM.
153 *
154 * The udp port usage may appear bizarre (well, ok, it is bizarre).
155 * The problem is that an icmp message only contains 8 bytes of
156 * data from the original datagram. 8 bytes is the size of a udp
157 * header so, if we want to associate replies with the original
158 * datagram, the necessary information must be encoded into the
159 * udp header (the ip id could be used but there's no way to
160 * interlock with the kernel's assignment of ip id's and, anyway,
161 * it would have taken a lot more kernel hacking to allow this
162 * code to set the ip id). So, to allow two or more users to
163 * use traceroute simultaneously, we use this task's pid as the
164 * source port (the high bit is set to move the port number out
165 * of the "likely" range). To keep track of which probe is being
166 * replied to (so times and/or hop counts don't get confused by a
167 * reply that was delayed in transit), we increment the destination
168 * port number before each probe.
169 *
170 * Don't use this as a coding example. I was trying to find a
171 * routing problem and this code sort-of popped out after 48 hours
172 * without sleep. I was amazed it ever compiled, much less ran.
173 *
174 * I stole the idea for this program from Steve Deering. Since
175 * the first release, I've learned that had I attended the right
176 * IETF working group meetings, I also could have stolen it from Guy
177 * Almes or Matt Mathis. I don't know (or care) who came up with
178 * the idea first. I envy the originators' perspicacity and I'm
179 * glad they didn't keep the idea a secret.
180 *
181 * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
182 * enhancements to the original distribution.
183 *
184 * I've hacked up a round-trip-route version of this that works by
185 * sending a loose-source-routed udp datagram through the destination
186 * back to yourself. Unfortunately, SO many gateways botch source
187 * routing, the thing is almost worthless. Maybe one day...
188 *
189 * -- Van Jacobson (van@ee.lbl.gov)
190 * Tue Dec 20 03:50:13 PST 1988
191 */
192
193 #include <sys/param.h>
194 #ifndef __HAIKU__
195 #include <sys/capsicum.h>
196 #endif
197 #include <sys/file.h>
198 #include <sys/ioctl.h>
199 #include <sys/select.h>
200 #include <sys/socket.h>
201 #ifndef __HAIKU__
202 #include <sys/sysctl.h>
203 #endif
204 #include <sys/time.h>
205
206 #ifndef __HAIKU__
207 #include <netinet/in_systm.h>
208 #endif
209 #include <netinet/in.h>
210 #include <netinet/ip.h>
211 #include <netinet/ip_var.h>
212 #include <netinet/ip_icmp.h>
213 #ifndef __HAIKU__
214 #include <netinet/sctp.h>
215 #include <netinet/sctp_header.h>
216 #endif
217 #include <netinet/udp.h>
218 #include <netinet/tcp.h>
219 #ifndef __HAIKU__
220 #include <netinet/tcpip.h>
221 #endif
222
223 #include <arpa/inet.h>
224
225 #ifdef WITH_CASPER
226 #include <libcasper.h>
227 #include <casper/cap_dns.h>
228 #endif
229
230 #ifdef IPSEC
231 #include <net/route.h>
232 #include <netipsec/ipsec.h> /* XXX */
233 #endif /* IPSEC */
234
235 #include <ctype.h>
236 #ifndef __HAIKU__
237 #include <capsicum_helpers.h>
238 #endif
239 #include <err.h>
240 #include <errno.h>
241 #include <fcntl.h>
242 #include <malloc.h>
243 #include <memory.h>
244 #include <netdb.h>
245 #include <stdio.h>
246 #include <stdlib.h>
247 #include <stdbool.h>
248 #include <string.h>
249 #include <unistd.h>
250
251 /* rfc1716 */
252 #ifndef ICMP_UNREACH_FILTER_PROHIB
253 #define ICMP_UNREACH_FILTER_PROHIB 13 /* admin prohibited filter */
254 #endif
255 #ifndef ICMP_UNREACH_HOST_PRECEDENCE
256 #define ICMP_UNREACH_HOST_PRECEDENCE 14 /* host precedence violation */
257 #endif
258 #ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF
259 #define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 /* precedence cutoff */
260 #endif
261
262 #include "findsaddr.h"
263 #include "ifaddrlist.h"
264 #include "as.h"
265 #include "traceroute.h"
266
267 /* Maximum number of gateways (include room for one noop) */
268 #define NGATEWAYS ((int)((MAX_IPOPTLEN - IPOPT_MINOFF - 1) / sizeof(u_int32_t)))
269
270 #ifndef MAXHOSTNAMELEN
271 #define MAXHOSTNAMELEN 64
272 #endif
273
274 #define Fprintf (void)fprintf
275 #define Printf (void)printf
276
277 /* What a GRE packet header looks like */
278 struct grehdr {
279 u_int16_t flags;
280 u_int16_t proto;
281 u_int16_t length; /* PPTP version of these fields */
282 u_int16_t callId;
283 };
284 #ifndef IPPROTO_GRE
285 #define IPPROTO_GRE 47
286 #endif
287
288 /* For GRE, we prepare what looks like a PPTP packet */
289 #define GRE_PPTP_PROTO 0x880b
290
291 /* Host name and address list */
292 struct hostinfo {
293 char *name;
294 int n;
295 u_int32_t *addrs;
296 };
297
298 /* Data section of the probe packet */
299 struct outdata {
300 u_char seq; /* sequence number of this packet */
301 u_char ttl; /* ttl packet left with */
302 struct timeval tv; /* time packet left */
303 };
304
305 u_char packet[512]; /* last inbound (icmp) packet */
306
307 struct ip *outip; /* last output ip packet */
308 u_char *outp; /* last output inner protocol packet */
309
310 struct ip *hip = NULL; /* Quoted IP header */
311 int hiplen = 0;
312
313 /* loose source route gateway list (including room for final destination) */
314 u_int32_t gwlist[NGATEWAYS + 1];
315
316 int s; /* receive (icmp) socket file descriptor */
317 int sndsock; /* send (udp) socket file descriptor */
318
319 struct sockaddr whereto; /* Who to try to reach */
320 struct sockaddr wherefrom; /* Who we are */
321 int packlen; /* total length of packet */
322 int protlen; /* length of protocol part of packet */
323 int minpacket; /* min ip packet size */
324 int maxpacket = 32 * 1024; /* max ip packet size */
325 int pmtu; /* Path MTU Discovery (RFC1191) */
326 u_int pausemsecs;
327
328 char *prog;
329 char *source;
330 char *hostname;
331 char *device;
332 static const char devnull[] = "/dev/null";
333
334 int nprobes = -1;
335 int max_ttl;
336 int first_ttl = 1;
337 u_short ident;
338 u_short port; /* protocol specific base "port" */
339
340 int options; /* socket options */
341 int verbose;
342 int waittime = 5; /* time to wait for response (in seconds) */
343 int nflag; /* print addresses numerically */
344 int as_path; /* print as numbers for each hop */
345 char *as_server = NULL;
346 void *asn;
347 #ifdef CANT_HACK_IPCKSUM
348 int doipcksum = 0; /* don't calculate ip checksums by default */
349 #else
350 int doipcksum = 1; /* calculate ip checksums by default */
351 #endif
352 int optlen; /* length of ip options */
353 int fixedPort = 0; /* Use fixed destination port for TCP and UDP */
354 int printdiff = 0; /* Print the difference between sent and quoted */
355 int ecnflag = 0; /* ECN bleaching detection flag */
356
357 extern int optind;
358 extern int opterr;
359 extern char *optarg;
360
361 #ifdef WITH_CASPER
362 static cap_channel_t *capdns;
363 #endif
364
365 /* Forwards */
366 double deltaT(struct timeval *, struct timeval *);
367 void freehostinfo(struct hostinfo *);
368 void getaddr(u_int32_t *, char *);
369 struct hostinfo *gethostinfo(char *);
370 u_short in_cksum(u_short *, int);
371 u_int32_t sctp_crc32c(const void *, u_int32_t);
372 char *inetname(struct in_addr);
373 int main(int, char **);
374 u_short p_cksum(struct ip *, u_short *, int, int);
375 int packet_ok(u_char *, int, struct sockaddr_in *, int);
376 char *pr_type(u_char);
377 void print(u_char *, int, struct sockaddr_in *);
378 #ifdef IPSEC
379 int setpolicy(int so, char *policy);
380 #endif
381 void send_probe(int, int);
382 struct outproto *setproto(char *);
383 int str2val(const char *, const char *, int, int);
384 void tvsub(struct timeval *, struct timeval *);
385 void usage(void);
386 int wait_for_reply(int, struct sockaddr_in *, const struct timeval *);
387 void pkt_compare(const u_char *, int, const u_char *, int);
388
389 void udp_prep(struct outdata *);
390 int udp_check(const u_char *, int);
391 void udplite_prep(struct outdata *);
392 int udplite_check(const u_char *, int);
393 void tcp_prep(struct outdata *);
394 int tcp_check(const u_char *, int);
395 void sctp_prep(struct outdata *);
396 int sctp_check(const u_char *, int);
397 void gre_prep(struct outdata *);
398 int gre_check(const u_char *, int);
399 void gen_prep(struct outdata *);
400 int gen_check(const u_char *, int);
401 void icmp_prep(struct outdata *);
402 int icmp_check(const u_char *, int);
403
404 /* Descriptor structure for each outgoing protocol we support */
405 struct outproto {
406 char *name; /* name of protocol */
407 const char *key; /* An ascii key for the bytes of the header */
408 u_char num; /* IP protocol number */
409 u_short hdrlen; /* max size of protocol header */
410 u_short port; /* default base protocol-specific "port" */
411 void (*prepare)(struct outdata *);
412 /* finish preparing an outgoing packet */
413 int (*check)(const u_char *, int);
414 /* check an incoming packet */
415 };
416
417 /* List of supported protocols. The first one is the default. The last
418 one is the handler for generic protocols not explicitly listed. */
419 struct outproto protos[] = {
420 {
421 "udp",
422 "spt dpt len sum",
423 IPPROTO_UDP,
424 sizeof(struct udphdr),
425 32768 + 666,
426 udp_prep,
427 udp_check
428 },
429 #ifndef __HAIKU__
430 {
431 "udplite",
432 "spt dpt cov sum",
433 IPPROTO_UDPLITE,
434 sizeof(struct udphdr),
435 32768 + 666,
436 udplite_prep,
437 udplite_check
438 },
439 #endif
440 {
441 "tcp",
442 "spt dpt seq ack xxflwin sum urp",
443 IPPROTO_TCP,
444 sizeof(struct tcphdr),
445 32768 + 666,
446 tcp_prep,
447 tcp_check
448 },
449 #ifndef __HAIKU__
450 {
451 "sctp",
452 "spt dpt vtag crc tyfllen tyfllen ",
453 IPPROTO_SCTP,
454 sizeof(struct sctphdr),
455 32768 + 666,
456 sctp_prep,
457 sctp_check
458 },
459 #endif
460 {
461 "gre",
462 "flg pro len clid",
463 IPPROTO_GRE,
464 sizeof(struct grehdr),
465 GRE_PPTP_PROTO,
466 gre_prep,
467 gre_check
468 },
469 {
470 "icmp",
471 "typ cod sum ",
472 IPPROTO_ICMP,
473 sizeof(struct icmp),
474 0,
475 icmp_prep,
476 icmp_check
477 },
478 {
479 NULL,
480 "",
481 0,
482 2 * sizeof(u_short),
483 0,
484 gen_prep,
485 gen_check
486 },
487 };
488 struct outproto *proto = &protos[0];
489
490 const char *ip_hdr_key = "vhtslen id off tlprsum srcip dstip opts";
491
492 int
main(int argc,char ** argv)493 main(int argc, char **argv)
494 {
495 register int op, code, n;
496 register char *cp;
497 register const char *err;
498 register u_int32_t *ap;
499 register struct sockaddr_in *from = (struct sockaddr_in *)&wherefrom;
500 register struct sockaddr_in *to = (struct sockaddr_in *)&whereto;
501 register struct hostinfo *hi;
502 int on = 1;
503 register struct protoent *pe;
504 register int ttl, probe, i;
505 register int seq = 0;
506 int tos = 0, settos = 0;
507 register int lsrr = 0;
508 register u_short off = 0;
509 struct ifaddrlist *al;
510 char errbuf[132];
511 int requestPort = -1;
512 int sump = 0;
513 int sockerrno;
514 #ifdef WITH_CASPER
515 const char *types[] = { "NAME2ADDR", "ADDR2NAME" };
516 int families[1];
517 cap_channel_t *casper;
518 #endif
519 #ifndef __HAIKU__
520 cap_rights_t rights;
521 #endif
522 bool cansandbox;
523
524 /* Insure the socket fds won't be 0, 1 or 2 */
525 if (open(devnull, O_RDONLY) < 0 ||
526 open(devnull, O_RDONLY) < 0 ||
527 open(devnull, O_RDONLY) < 0) {
528 Fprintf(stderr, "%s: open \"%s\": %s\n",
529 prog, devnull, strerror(errno));
530 exit(1);
531 }
532 /*
533 * Do the setuid-required stuff first, then lose privileges ASAP.
534 * Do error checking for these two calls where they appeared in
535 * the original code.
536 */
537 cp = "icmp";
538 pe = getprotobyname(cp);
539 if (pe) {
540 if ((s = socket(AF_INET, SOCK_RAW, pe->p_proto)) < 0)
541 sockerrno = errno;
542 else if ((sndsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
543 sockerrno = errno;
544 }
545
546 if (setuid(getuid()) != 0) {
547 perror("setuid()");
548 exit(1);
549 }
550
551 #ifdef WITH_CASPER
552 casper = cap_init();
553 if (casper == NULL)
554 errx(1, "unable to create casper process");
555 capdns = cap_service_open(casper, "system.dns");
556 if (capdns == NULL)
557 errx(1, "unable to open system.dns service");
558 if (cap_dns_type_limit(capdns, types, 2) < 0)
559 errx(1, "unable to limit access to system.dns service");
560 families[0] = AF_INET;
561 if (cap_dns_family_limit(capdns, families, 1) < 0)
562 errx(1, "unable to limit access to system.dns service");
563 #endif /* WITH_CASPER */
564
565 #ifdef IPCTL_DEFTTL
566 {
567 int mib[4] = { CTL_NET, PF_INET, IPPROTO_IP, IPCTL_DEFTTL };
568 size_t sz = sizeof(max_ttl);
569
570 if (sysctl(mib, 4, &max_ttl, &sz, NULL, 0) == -1) {
571 perror("sysctl(net.inet.ip.ttl)");
572 exit(1);
573 }
574 }
575 #else /* !IPCTL_DEFTTL */
576 max_ttl = 30;
577 #endif
578
579 #ifdef WITH_CASPER
580 cap_close(casper);
581 #endif
582
583 if (argv[0] == NULL)
584 prog = "traceroute";
585 else if ((cp = strrchr(argv[0], '/')) != NULL)
586 prog = cp + 1;
587 else
588 prog = argv[0];
589
590 opterr = 0;
591 while ((op = getopt(argc, argv, "aA:edDFInrSvxf:g:i:M:m:P:p:q:s:t:w:z:")) != EOF)
592 switch (op) {
593 case 'a':
594 as_path = 1;
595 break;
596
597 case 'A':
598 as_path = 1;
599 as_server = optarg;
600 break;
601
602 case 'd':
603 options |= SO_DEBUG;
604 break;
605
606 case 'D':
607 printdiff = 1;
608 break;
609
610 case 'e':
611 fixedPort = 1;
612 break;
613
614 #ifndef __HAIKU__
615 case 'E':
616 ecnflag = 1;
617 break;
618 #endif
619
620 case 'f':
621 case 'M': /* FreeBSD compat. */
622 first_ttl = str2val(optarg, "first ttl", 1, 255);
623 break;
624
625 case 'F':
626 off = IP_DF;
627 break;
628
629 case 'g':
630 if (lsrr >= NGATEWAYS) {
631 Fprintf(stderr,
632 "%s: No more than %d gateways\n",
633 prog, NGATEWAYS);
634 exit(1);
635 }
636 getaddr(gwlist + lsrr, optarg);
637 ++lsrr;
638 break;
639
640 case 'i':
641 device = optarg;
642 break;
643
644 case 'I':
645 proto = setproto("icmp");
646 break;
647
648 case 'm':
649 max_ttl = str2val(optarg, "max ttl", 1, 255);
650 break;
651
652 case 'n':
653 ++nflag;
654 break;
655
656 case 'P':
657 proto = setproto(optarg);
658 break;
659
660 case 'p':
661 requestPort = (u_short)str2val(optarg, "port",
662 1, (1 << 16) - 1);
663 break;
664
665 case 'q':
666 nprobes = str2val(optarg, "nprobes", 1, -1);
667 break;
668
669 case 'r':
670 options |= SO_DONTROUTE;
671 break;
672
673 case 's':
674 /*
675 * set the ip source address of the outbound
676 * probe (e.g., on a multi-homed host).
677 */
678 source = optarg;
679 break;
680
681 case 'S':
682 sump = 1;
683 break;
684
685 case 't':
686 tos = str2val(optarg, "tos", 0, 255);
687 ++settos;
688 break;
689
690 case 'v':
691 ++verbose;
692 break;
693
694 case 'x':
695 doipcksum = (doipcksum == 0);
696 break;
697
698 case 'w':
699 waittime = str2val(optarg, "wait time",
700 1, 24 * 60 * 60);
701 break;
702
703 case 'z':
704 pausemsecs = str2val(optarg, "pause msecs",
705 0, 60 * 60 * 1000);
706 break;
707
708 default:
709 usage();
710 }
711
712 /* Set requested port, if any, else default for this protocol */
713 port = (requestPort != -1) ? requestPort : proto->port;
714
715 if (nprobes == -1)
716 nprobes = printdiff ? 1 : 3;
717
718 if (first_ttl > max_ttl) {
719 Fprintf(stderr,
720 "%s: first ttl (%d) may not be greater than max ttl (%d)\n",
721 prog, first_ttl, max_ttl);
722 exit(1);
723 }
724
725 if (!doipcksum)
726 Fprintf(stderr, "%s: Warning: ip checksums disabled\n", prog);
727
728 if (lsrr > 0)
729 optlen = (lsrr + 1) * sizeof(gwlist[0]);
730 minpacket = sizeof(*outip) + proto->hdrlen + optlen;
731 if (minpacket > 40)
732 packlen = minpacket;
733 else
734 packlen = 40;
735
736 /* Process destination and optional packet size */
737 switch (argc - optind) {
738
739 case 2:
740 packlen = str2val(argv[optind + 1],
741 "packet length", minpacket, maxpacket);
742 /* Fall through */
743
744 case 1:
745 hostname = argv[optind];
746 hi = gethostinfo(hostname);
747 setsin(to, hi->addrs[0]);
748 if (hi->n > 1)
749 Fprintf(stderr,
750 "%s: Warning: %s has multiple addresses; using %s\n",
751 prog, hostname, inet_ntoa(to->sin_addr));
752 hostname = hi->name;
753 hi->name = NULL;
754 freehostinfo(hi);
755 break;
756
757 default:
758 usage();
759 }
760
761 setlinebuf(stdout);
762
763 protlen = packlen - sizeof(*outip) - optlen;
764 #ifndef __HAIKU__
765 if ((proto->num == IPPROTO_SCTP) && (packlen & 3)) {
766 Fprintf(stderr, "%s: packet length must be a multiple of 4\n",
767 prog);
768 exit(1);
769 }
770 #endif
771
772 outip = (struct ip *)malloc((unsigned)packlen);
773 if (outip == NULL) {
774 Fprintf(stderr, "%s: malloc: %s\n", prog, strerror(errno));
775 exit(1);
776 }
777 memset((char *)outip, 0, packlen);
778
779 outip->ip_v = IPVERSION;
780 if (settos)
781 outip->ip_tos = tos;
782 #ifndef __HAIKU__
783 if (ecnflag) {
784 outip->ip_tos &= ~IPTOS_ECN_MASK;
785 outip->ip_tos |= IPTOS_ECN_ECT1;
786 }
787 #endif
788 outip->ip_len = htons(packlen);
789 outip->ip_off = htons(off);
790 outip->ip_p = proto->num;
791 outp = (u_char *)(outip + 1);
792 if (lsrr > 0) {
793 register u_char *optlist;
794
795 optlist = outp;
796 outp += optlen;
797
798 /* final hop */
799 gwlist[lsrr] = to->sin_addr.s_addr;
800
801 outip->ip_dst.s_addr = gwlist[0];
802
803 /* force 4 byte alignment */
804 optlist[0] = IPOPT_NOP;
805 /* loose source route option */
806 optlist[1] = IPOPT_LSRR;
807 i = lsrr * sizeof(gwlist[0]);
808 optlist[2] = i + 3;
809 /* Pointer to LSRR addresses */
810 optlist[3] = IPOPT_MINOFF;
811 memcpy(optlist + 4, gwlist + 1, i);
812 } else
813 outip->ip_dst = to->sin_addr;
814
815 outip->ip_hl = (outp - (u_char *)outip) >> 2;
816 ident = (getpid() & 0xffff) | 0x8000;
817
818 if (pe == NULL) {
819 Fprintf(stderr, "%s: unknown protocol %s\n", prog, cp);
820 exit(1);
821 }
822 if (s < 0) {
823 errno = sockerrno;
824 Fprintf(stderr, "%s: icmp socket: %s\n", prog, strerror(errno));
825 exit(1);
826 }
827 if (options & SO_DEBUG)
828 (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&on,
829 sizeof(on));
830 if (options & SO_DONTROUTE)
831 (void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&on,
832 sizeof(on));
833
834 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
835 if (setpolicy(s, "in bypass") < 0)
836 errx(1, "%s", ipsec_strerror());
837
838 if (setpolicy(s, "out bypass") < 0)
839 errx(1, "%s", ipsec_strerror());
840 #endif /* defined(IPSEC) && defined(IPSEC_POLICY_IPSEC) */
841
842 if (sndsock < 0) {
843 errno = sockerrno;
844 Fprintf(stderr, "%s: raw socket: %s\n", prog, strerror(errno));
845 exit(1);
846 }
847
848 #ifdef SO_SNDBUF
849 if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&packlen,
850 sizeof(packlen)) < 0) {
851 Fprintf(stderr, "%s: SO_SNDBUF: %s\n", prog, strerror(errno));
852 exit(1);
853 }
854 #endif
855 #ifdef IP_HDRINCL
856 if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL, (char *)&on,
857 sizeof(on)) < 0) {
858 Fprintf(stderr, "%s: IP_HDRINCL: %s\n", prog, strerror(errno));
859 exit(1);
860 }
861 #else
862 #ifdef IP_TOS
863 if (settos && setsockopt(sndsock, IPPROTO_IP, IP_TOS,
864 (char *)&tos, sizeof(tos)) < 0) {
865 Fprintf(stderr, "%s: setsockopt tos %d: %s\n",
866 prog, tos, strerror(errno));
867 exit(1);
868 }
869 #endif
870 #endif
871 if (options & SO_DEBUG)
872 (void)setsockopt(sndsock, SOL_SOCKET, SO_DEBUG, (char *)&on,
873 sizeof(on));
874 if (options & SO_DONTROUTE)
875 (void)setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE, (char *)&on,
876 sizeof(on));
877
878 /* Get the interface address list */
879 n = ifaddrlist(&al, errbuf);
880 if (n < 0) {
881 Fprintf(stderr, "%s: ifaddrlist: %s\n", prog, errbuf);
882 exit(1);
883 }
884 if (n == 0) {
885 Fprintf(stderr,
886 "%s: Can't find any network interfaces\n", prog);
887 exit(1);
888 }
889
890 /* Look for a specific device */
891 if (device != NULL) {
892 for (i = n; i > 0; --i, ++al)
893 if (strcmp(device, al->device) == 0)
894 break;
895 if (i <= 0) {
896 Fprintf(stderr, "%s: Can't find interface %.32s\n",
897 prog, device);
898 exit(1);
899 }
900 }
901
902 /* Determine our source address */
903 if (source == NULL) {
904 /*
905 * If a device was specified, use the interface address.
906 * Otherwise, try to determine our source address.
907 */
908 if (device != NULL)
909 setsin(from, al->addr);
910 else if ((err = findsaddr(to, from)) != NULL) {
911 Fprintf(stderr, "%s: findsaddr: %s\n",
912 prog, err);
913 exit(1);
914 }
915 } else {
916 hi = gethostinfo(source);
917 source = hi->name;
918 hi->name = NULL;
919 /*
920 * If the device was specified make sure it
921 * corresponds to the source address specified.
922 * Otherwise, use the first address (and warn if
923 * there are more than one).
924 */
925 if (device != NULL) {
926 for (i = hi->n, ap = hi->addrs; i > 0; --i, ++ap)
927 if (*ap == al->addr)
928 break;
929 if (i <= 0) {
930 Fprintf(stderr,
931 "%s: %s is not on interface %.32s\n",
932 prog, source, device);
933 exit(1);
934 }
935 setsin(from, *ap);
936 } else {
937 setsin(from, hi->addrs[0]);
938 if (hi->n > 1)
939 Fprintf(stderr,
940 "%s: Warning: %s has multiple addresses; using %s\n",
941 prog, source, inet_ntoa(from->sin_addr));
942 }
943 freehostinfo(hi);
944 }
945
946 outip->ip_src = from->sin_addr;
947
948 /* Check the source address (-s), if any, is valid */
949 if (bind(sndsock, (struct sockaddr *)from, sizeof(*from)) < 0) {
950 Fprintf(stderr, "%s: bind: %s\n",
951 prog, strerror(errno));
952 exit(1);
953 }
954
955 if (as_path) {
956 asn = as_setup(as_server);
957 if (asn == NULL) {
958 Fprintf(stderr, "%s: as_setup failed, AS# lookups"
959 " disabled\n", prog);
960 (void)fflush(stderr);
961 as_path = 0;
962 }
963 }
964
965 #ifndef __HAIKU__
966 if (connect(sndsock, (struct sockaddr *)&whereto,
967 sizeof(whereto)) != 0) {
968 Fprintf(stderr, "%s: connect: %s\n", prog, strerror(errno));
969 exit(1);
970 }
971 #endif
972
973 #ifdef WITH_CASPER
974 cansandbox = true;
975 #else
976 if (nflag)
977 cansandbox = true;
978 else
979 cansandbox = false;
980 #endif
981
982 #ifndef __HAIKU__
983 caph_cache_catpages();
984
985 /*
986 * Here we enter capability mode. Further down access to global
987 * namespaces (e.g filesystem) is restricted (see capsicum(4)).
988 * We must connect(2) our socket before this point.
989 */
990 if (cansandbox && cap_enter() < 0) {
991 if (errno != ENOSYS) {
992 Fprintf(stderr, "%s: cap_enter: %s\n", prog,
993 strerror(errno));
994 exit(1);
995 } else {
996 cansandbox = false;
997 }
998 }
999
1000 cap_rights_init(&rights, CAP_SEND, CAP_SETSOCKOPT);
1001 if (cansandbox && cap_rights_limit(sndsock, &rights) < 0) {
1002 Fprintf(stderr, "%s: cap_rights_limit sndsock: %s\n", prog,
1003 strerror(errno));
1004 exit(1);
1005 }
1006
1007 cap_rights_init(&rights, CAP_RECV, CAP_EVENT);
1008 if (cansandbox && cap_rights_limit(s, &rights) < 0) {
1009 Fprintf(stderr, "%s: cap_rights_limit s: %s\n", prog,
1010 strerror(errno));
1011 exit(1);
1012 }
1013 #endif
1014
1015 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
1016 if (setpolicy(sndsock, "in bypass") < 0)
1017 errx(1, "%s", ipsec_strerror());
1018
1019 if (setpolicy(sndsock, "out bypass") < 0)
1020 errx(1, "%s", ipsec_strerror());
1021 #endif /* defined(IPSEC) && defined(IPSEC_POLICY_IPSEC) */
1022
1023 Fprintf(stderr, "%s to %s (%s)",
1024 prog, hostname, inet_ntoa(to->sin_addr));
1025 if (source)
1026 Fprintf(stderr, " from %s", source);
1027 Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl, packlen);
1028 (void)fflush(stderr);
1029
1030 for (ttl = first_ttl; ttl <= max_ttl; ++ttl) {
1031 u_int32_t lastaddr = 0;
1032 int gotlastaddr = 0;
1033 int got_there = 0;
1034 int unreachable = 0;
1035 int sentfirst = 0;
1036 int loss;
1037
1038 Printf("%2d ", ttl);
1039 for (probe = 0, loss = 0; probe < nprobes; ++probe) {
1040 register int cc;
1041 struct timeval t1, t2;
1042 register struct ip *ip;
1043 struct outdata outdata;
1044
1045 if (sentfirst && pausemsecs > 0)
1046 usleep(pausemsecs * 1000);
1047 /* Prepare outgoing data */
1048 outdata.seq = ++seq;
1049 outdata.ttl = ttl;
1050
1051 /* Avoid alignment problems by copying bytewise: */
1052 (void)gettimeofday(&t1, NULL);
1053 memcpy(&outdata.tv, &t1, sizeof(outdata.tv));
1054
1055 /* Finalize and send packet */
1056 (*proto->prepare)(&outdata);
1057 send_probe(seq, ttl);
1058 ++sentfirst;
1059
1060 /* Wait for a reply */
1061 while ((cc = wait_for_reply(s, from, &t1)) != 0) {
1062 double T;
1063 int precis;
1064
1065 (void)gettimeofday(&t2, NULL);
1066 i = packet_ok(packet, cc, from, seq);
1067 /* Skip short packet */
1068 if (i == 0)
1069 continue;
1070 if (!gotlastaddr ||
1071 from->sin_addr.s_addr != lastaddr) {
1072 if (gotlastaddr)
1073 printf("\n ");
1074 print(packet, cc, from);
1075 lastaddr = from->sin_addr.s_addr;
1076 ++gotlastaddr;
1077 }
1078 T = deltaT(&t1, &t2);
1079 #ifdef SANE_PRECISION
1080 if (T >= 1000.0)
1081 precis = 0;
1082 else if (T >= 100.0)
1083 precis = 1;
1084 else if (T >= 10.0)
1085 precis = 2;
1086 else
1087 #endif
1088 precis = 3;
1089 Printf(" %.*f ms", precis, T);
1090 #ifndef __HAIKU__
1091 if (ecnflag) {
1092 u_char ecn = hip->ip_tos & IPTOS_ECN_MASK;
1093 switch (ecn) {
1094 case IPTOS_ECN_ECT1:
1095 Printf(" (ecn=passed)");
1096 break;
1097 case IPTOS_ECN_NOTECT:
1098 Printf(" (ecn=bleached)");
1099 break;
1100 case IPTOS_ECN_CE:
1101 Printf(" (ecn=congested)");
1102 break;
1103 default:
1104 Printf(" (ecn=mangled)");
1105 break;
1106 }
1107 }
1108 #endif
1109 if (printdiff) {
1110 Printf("\n");
1111 Printf("%*.*s%s\n",
1112 -(outip->ip_hl << 3),
1113 outip->ip_hl << 3,
1114 ip_hdr_key,
1115 proto->key);
1116 pkt_compare((void *)outip, packlen,
1117 (void *)hip, hiplen);
1118 }
1119 if (i == -2) {
1120 #ifndef ARCHAIC
1121 ip = (struct ip *)packet;
1122 if (ip->ip_ttl <= 1)
1123 Printf(" !");
1124 #endif
1125 ++got_there;
1126 break;
1127 }
1128 /* time exceeded in transit */
1129 if (i == -1)
1130 break;
1131 code = i - 1;
1132 switch (code) {
1133
1134 case ICMP_UNREACH_PORT:
1135 #ifndef ARCHAIC
1136 ip = (struct ip *)packet;
1137 if (ip->ip_ttl <= 1)
1138 Printf(" !");
1139 #endif
1140 ++got_there;
1141 break;
1142
1143 case ICMP_UNREACH_NET:
1144 ++unreachable;
1145 Printf(" !N");
1146 break;
1147
1148 case ICMP_UNREACH_HOST:
1149 ++unreachable;
1150 Printf(" !H");
1151 break;
1152
1153 case ICMP_UNREACH_PROTOCOL:
1154 ++got_there;
1155 Printf(" !P");
1156 break;
1157
1158 case ICMP_UNREACH_NEEDFRAG:
1159 ++unreachable;
1160 Printf(" !F-%d", pmtu);
1161 break;
1162
1163 case ICMP_UNREACH_SRCFAIL:
1164 ++unreachable;
1165 Printf(" !S");
1166 break;
1167
1168 case ICMP_UNREACH_NET_UNKNOWN:
1169 ++unreachable;
1170 Printf(" !U");
1171 break;
1172
1173 case ICMP_UNREACH_HOST_UNKNOWN:
1174 ++unreachable;
1175 Printf(" !W");
1176 break;
1177
1178 case ICMP_UNREACH_ISOLATED:
1179 ++unreachable;
1180 Printf(" !I");
1181 break;
1182
1183 case ICMP_UNREACH_NET_PROHIB:
1184 ++unreachable;
1185 Printf(" !A");
1186 break;
1187
1188 case ICMP_UNREACH_HOST_PROHIB:
1189 ++unreachable;
1190 Printf(" !Z");
1191 break;
1192
1193 case ICMP_UNREACH_TOSNET:
1194 ++unreachable;
1195 Printf(" !Q");
1196 break;
1197
1198 case ICMP_UNREACH_TOSHOST:
1199 ++unreachable;
1200 Printf(" !T");
1201 break;
1202
1203 case ICMP_UNREACH_FILTER_PROHIB:
1204 ++unreachable;
1205 Printf(" !X");
1206 break;
1207
1208 case ICMP_UNREACH_HOST_PRECEDENCE:
1209 ++unreachable;
1210 Printf(" !V");
1211 break;
1212
1213 case ICMP_UNREACH_PRECEDENCE_CUTOFF:
1214 ++unreachable;
1215 Printf(" !C");
1216 break;
1217
1218 default:
1219 ++unreachable;
1220 Printf(" !<%d>", code);
1221 break;
1222 }
1223 break;
1224 }
1225 if (cc == 0) {
1226 loss++;
1227 Printf(" *");
1228 }
1229 (void)fflush(stdout);
1230 }
1231 if (sump) {
1232 Printf(" (%d%% loss)", (loss * 100) / nprobes);
1233 }
1234 putchar('\n');
1235 if (got_there ||
1236 (unreachable > 0 && unreachable >= nprobes - 1))
1237 break;
1238 }
1239 if (as_path)
1240 as_shutdown(asn);
1241 exit(0);
1242 }
1243
1244 int
wait_for_reply(register int sock,register struct sockaddr_in * fromp,register const struct timeval * tp)1245 wait_for_reply(register int sock, register struct sockaddr_in *fromp,
1246 register const struct timeval *tp)
1247 {
1248 fd_set *fdsp;
1249 size_t nfds;
1250 struct timeval now, wait;
1251 register int cc = 0;
1252 register int error;
1253 int fromlen = sizeof(*fromp);
1254
1255 nfds = howmany(sock + 1, NFDBITS);
1256 if ((fdsp = malloc(nfds * sizeof(fd_mask))) == NULL)
1257 err(1, "malloc");
1258 memset(fdsp, 0, nfds * sizeof(fd_mask));
1259 FD_SET(sock, fdsp);
1260
1261 wait.tv_sec = tp->tv_sec + waittime;
1262 wait.tv_usec = tp->tv_usec;
1263 (void)gettimeofday(&now, NULL);
1264 tvsub(&wait, &now);
1265 if (wait.tv_sec < 0) {
1266 wait.tv_sec = 0;
1267 wait.tv_usec = 1;
1268 }
1269
1270 error = select(sock + 1, fdsp, NULL, NULL, &wait);
1271 if (error == -1 && errno == EINVAL) {
1272 Fprintf(stderr, "%s: botched select() args\n", prog);
1273 exit(1);
1274 }
1275 if (error > 0)
1276 cc = recvfrom(sock, (char *)packet, sizeof(packet), 0,
1277 (struct sockaddr *)fromp, &fromlen);
1278
1279 free(fdsp);
1280 return (cc);
1281 }
1282
1283 void
send_probe(int seq,int ttl)1284 send_probe(int seq, int ttl)
1285 {
1286 register int cc;
1287
1288 outip->ip_ttl = ttl;
1289 outip->ip_id = htons(ident + seq);
1290
1291 /* XXX undocumented debugging hack */
1292 if (verbose > 1) {
1293 register const u_short *sp;
1294 register int nshorts, i;
1295
1296 sp = (u_short *)outip;
1297 nshorts = (u_int)packlen / sizeof(u_short);
1298 i = 0;
1299 Printf("[ %d bytes", packlen);
1300 while (--nshorts >= 0) {
1301 if ((i++ % 8) == 0)
1302 Printf("\n\t");
1303 Printf(" %04x", ntohs(*sp++));
1304 }
1305 if (packlen & 1) {
1306 if ((i % 8) == 0)
1307 Printf("\n\t");
1308 Printf(" %02x", *(u_char *)sp);
1309 }
1310 Printf("]\n");
1311 }
1312
1313 #if !defined(IP_HDRINCL) && defined(IP_TTL)
1314 if (setsockopt(sndsock, IPPROTO_IP, IP_TTL,
1315 (char *)&ttl, sizeof(ttl)) < 0) {
1316 Fprintf(stderr, "%s: setsockopt ttl %d: %s\n",
1317 prog, ttl, strerror(errno));
1318 exit(1);
1319 }
1320 #endif
1321
1322 #ifndef __HAIKU__
1323 cc = send(sndsock, (char *)outip, packlen, 0);
1324 #else
1325 cc = sendto(sndsock, (char *)outip, packlen, 0, &whereto,
1326 sizeof(struct sockaddr));
1327 #endif
1328
1329 if (cc < 0 || cc != packlen) {
1330 if (cc < 0)
1331 Fprintf(stderr, "%s: sendto: %s\n",
1332 prog, strerror(errno));
1333 Printf("%s: wrote %s %d chars, ret=%d\n",
1334 prog, hostname, packlen, cc);
1335 (void)fflush(stdout);
1336 }
1337 }
1338
1339 #if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC)
1340 int
setpolicy(int so,char * policy)1341 setpolicy(int so, char *policy)
1342 {
1343 char *buf;
1344
1345 buf = ipsec_set_policy(policy, strlen(policy));
1346 if (buf == NULL) {
1347 warnx("%s", ipsec_strerror());
1348 return (-1);
1349 }
1350 (void)setsockopt(so, IPPROTO_IP, IP_IPSEC_POLICY,
1351 buf, ipsec_get_policylen(buf));
1352
1353 free(buf);
1354
1355 return (0);
1356 }
1357 #endif
1358
1359 double
deltaT(struct timeval * t1p,struct timeval * t2p)1360 deltaT(struct timeval *t1p, struct timeval *t2p)
1361 {
1362 register double dt;
1363
1364 dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
1365 (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
1366 return (dt);
1367 }
1368
1369 /*
1370 * Convert an ICMP "type" field to a printable string.
1371 */
1372 char *
pr_type(register u_char t)1373 pr_type(register u_char t)
1374 {
1375 static char *ttab[] = {
1376 "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
1377 "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
1378 "Echo", "ICMP 9", "ICMP 10", "Time Exceeded",
1379 "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
1380 "Info Reply"
1381 };
1382
1383 if (t > 16)
1384 return ("OUT-OF-RANGE");
1385
1386 return (ttab[t]);
1387 }
1388
1389 int
packet_ok(register u_char * buf,int cc,register struct sockaddr_in * from,register int seq)1390 packet_ok(register u_char *buf, int cc, register struct sockaddr_in *from,
1391 register int seq)
1392 {
1393 register struct icmp *icp;
1394 register u_char type, code;
1395 register int hlen;
1396 #ifndef ARCHAIC
1397 register struct ip *ip;
1398
1399 ip = (struct ip *) buf;
1400 hlen = ip->ip_hl << 2;
1401 if (cc < hlen + ICMP_MINLEN) {
1402 if (verbose)
1403 Printf("packet too short (%d bytes) from %s\n", cc,
1404 inet_ntoa(from->sin_addr));
1405 return (0);
1406 }
1407 cc -= hlen;
1408 icp = (struct icmp *)(buf + hlen);
1409 #else
1410 icp = (struct icmp *)buf;
1411 #endif
1412 type = icp->icmp_type;
1413 code = icp->icmp_code;
1414 /* Path MTU Discovery (RFC1191) */
1415 if (code != ICMP_UNREACH_NEEDFRAG)
1416 pmtu = 0;
1417 else {
1418 pmtu = ntohs(icp->icmp_nextmtu);
1419 }
1420 if (type == ICMP_ECHOREPLY
1421 && proto->num == IPPROTO_ICMP
1422 && (*proto->check)((u_char *)icp, (u_char)seq))
1423 return (-2);
1424 if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS) ||
1425 type == ICMP_UNREACH) {
1426 u_char *inner;
1427
1428 hip = &icp->icmp_ip;
1429 hiplen = ((u_char *)icp + cc) - (u_char *)hip;
1430 hlen = hip->ip_hl << 2;
1431 inner = (u_char *)((u_char *)hip + hlen);
1432 if (hlen + 16 <= cc
1433 && hip->ip_p == proto->num
1434 && (*proto->check)(inner, (u_char)seq))
1435 return (type == ICMP_TIMXCEED ? -1 : code + 1);
1436 }
1437 #ifndef ARCHAIC
1438 if (verbose) {
1439 register int i;
1440 u_int32_t *lp = (u_int32_t *)&icp->icmp_ip;
1441
1442 Printf("\n%d bytes from %s to ", cc, inet_ntoa(from->sin_addr));
1443 Printf("%s: icmp type %d (%s) code %d\n",
1444 inet_ntoa(ip->ip_dst), type, pr_type(type), icp->icmp_code);
1445 for (i = 4; i <= cc - ICMP_MINLEN; i += sizeof(*lp))
1446 Printf("%2d: %8.8x\n", i, ntohl(*lp++));
1447 }
1448 #endif
1449 return (0);
1450 }
1451
1452 void
icmp_prep(struct outdata * outdata)1453 icmp_prep(struct outdata *outdata)
1454 {
1455 struct icmp *const icmpheader = (struct icmp *) outp;
1456
1457 icmpheader->icmp_type = ICMP_ECHO;
1458 icmpheader->icmp_id = htons(ident);
1459 icmpheader->icmp_seq = htons(outdata->seq);
1460 icmpheader->icmp_cksum = 0;
1461 icmpheader->icmp_cksum = in_cksum((u_short *)icmpheader, protlen);
1462 if (icmpheader->icmp_cksum == 0)
1463 icmpheader->icmp_cksum = 0xffff;
1464 }
1465
1466 int
icmp_check(const u_char * data,int seq)1467 icmp_check(const u_char *data, int seq)
1468 {
1469 struct icmp *const icmpheader = (struct icmp *) data;
1470
1471 return (icmpheader->icmp_id == htons(ident)
1472 && icmpheader->icmp_seq == htons(seq));
1473 }
1474
1475 void
udp_prep(struct outdata * outdata)1476 udp_prep(struct outdata *outdata)
1477 {
1478 struct udphdr *const outudp = (struct udphdr *) outp;
1479
1480 outudp->uh_sport = htons(ident + (fixedPort ? outdata->seq : 0));
1481 outudp->uh_dport = htons(port + (fixedPort ? 0 : outdata->seq));
1482 outudp->uh_ulen = htons((u_short)protlen);
1483 outudp->uh_sum = 0;
1484 if (doipcksum) {
1485 u_short sum = p_cksum(outip, (u_short *)outudp, protlen, protlen);
1486 outudp->uh_sum = (sum) ? sum : 0xffff;
1487 }
1488
1489 return;
1490 }
1491
1492 int
udp_check(const u_char * data,int seq)1493 udp_check(const u_char *data, int seq)
1494 {
1495 struct udphdr *const udp = (struct udphdr *) data;
1496
1497 return (ntohs(udp->uh_sport) == ident + (fixedPort ? seq : 0) &&
1498 ntohs(udp->uh_dport) == port + (fixedPort ? 0 : seq));
1499 }
1500
1501 void
udplite_prep(struct outdata * outdata)1502 udplite_prep(struct outdata *outdata)
1503 {
1504 struct udphdr *const outudp = (struct udphdr *) outp;
1505
1506 outudp->uh_sport = htons(ident + (fixedPort ? outdata->seq : 0));
1507 outudp->uh_dport = htons(port + (fixedPort ? 0 : outdata->seq));
1508 outudp->uh_ulen = htons(8);
1509 outudp->uh_sum = 0;
1510 if (doipcksum) {
1511 u_short sum = p_cksum(outip, (u_short *)outudp, protlen, 8);
1512 outudp->uh_sum = (sum) ? sum : 0xffff;
1513 }
1514
1515 return;
1516 }
1517
1518 int
udplite_check(const u_char * data,int seq)1519 udplite_check(const u_char *data, int seq)
1520 {
1521 struct udphdr *const udp = (struct udphdr *) data;
1522
1523 return (ntohs(udp->uh_sport) == ident + (fixedPort ? seq : 0) &&
1524 ntohs(udp->uh_dport) == port + (fixedPort ? 0 : seq));
1525 }
1526
1527 void
tcp_prep(struct outdata * outdata)1528 tcp_prep(struct outdata *outdata)
1529 {
1530 struct tcphdr *const tcp = (struct tcphdr *) outp;
1531
1532 tcp->th_sport = htons(ident);
1533 tcp->th_dport = htons(port + (fixedPort ? 0 : outdata->seq));
1534 tcp->th_seq = (tcp->th_sport << 16) | tcp->th_dport;
1535 tcp->th_ack = 0;
1536 tcp->th_off = 5;
1537 tcp->th_flags = 0x02; /* TH_SYN */
1538 tcp->th_sum = 0;
1539
1540 if (doipcksum)
1541 tcp->th_sum = p_cksum(outip, (u_short *)tcp, protlen, protlen);
1542 }
1543
1544 int
tcp_check(const u_char * data,int seq)1545 tcp_check(const u_char *data, int seq)
1546 {
1547 struct tcphdr *const tcp = (struct tcphdr *) data;
1548
1549 return (ntohs(tcp->th_sport) == ident
1550 && ntohs(tcp->th_dport) == port + (fixedPort ? 0 : seq)
1551 && tcp->th_seq == (u_int32_t)((tcp->th_sport << 16) | tcp->th_dport));
1552 }
1553
1554 #ifndef __HAIKU__
1555 void
sctp_prep(struct outdata * outdata)1556 sctp_prep(struct outdata *outdata)
1557 {
1558 struct sctphdr *const sctp = (struct sctphdr *) outp;
1559 struct sctp_chunkhdr *chk;
1560 struct sctp_init_chunk *init;
1561 struct sctp_paramhdr *param;
1562
1563 sctp->src_port = htons(ident);
1564 sctp->dest_port = htons(port + (fixedPort ? 0 : outdata->seq));
1565 if (protlen >= (int)(sizeof(struct sctphdr) +
1566 sizeof(struct sctp_init_chunk))) {
1567 sctp->v_tag = 0;
1568 } else {
1569 sctp->v_tag = (sctp->src_port << 16) | sctp->dest_port;
1570 }
1571 sctp->checksum = htonl(0);
1572 if (protlen >= (int)(sizeof(struct sctphdr) +
1573 sizeof(struct sctp_init_chunk))) {
1574 /*
1575 * Send a packet containing an INIT chunk. This works
1576 * better in case of firewalls on the path, but
1577 * results in a probe packet containing at least
1578 * 32 bytes of payload. For shorter payloads, use
1579 * SHUTDOWN-ACK chunks.
1580 */
1581 init = (struct sctp_init_chunk *)(sctp + 1);
1582 init->ch.chunk_type = SCTP_INITIATION;
1583 init->ch.chunk_flags = 0;
1584 init->ch.chunk_length = htons((u_int16_t)(protlen -
1585 sizeof(struct sctphdr)));
1586 init->init.initiate_tag = (sctp->src_port << 16) |
1587 sctp->dest_port;
1588 init->init.a_rwnd = htonl(1500);
1589 init->init.num_outbound_streams = htons(1);
1590 init->init.num_inbound_streams = htons(1);
1591 init->init.initial_tsn = htonl(0);
1592 if (protlen >= (int)(sizeof(struct sctphdr) +
1593 sizeof(struct sctp_init_chunk) +
1594 sizeof(struct sctp_paramhdr))) {
1595 param = (struct sctp_paramhdr *)(init + 1);
1596 param->param_type = htons(SCTP_PAD);
1597 param->param_length =
1598 htons((u_int16_t)(protlen -
1599 sizeof(struct sctphdr) -
1600 sizeof(struct sctp_init_chunk)));
1601 }
1602 } else {
1603 /*
1604 * Send a packet containing a SHUTDOWN-ACK chunk,
1605 * possibly followed by a PAD chunk.
1606 */
1607 if (protlen >=
1608 (int)(sizeof(struct sctphdr) +
1609 sizeof(struct sctp_chunkhdr))) {
1610 chk = (struct sctp_chunkhdr *)(sctp + 1);
1611 chk->chunk_type = SCTP_SHUTDOWN_ACK;
1612 chk->chunk_flags = 0;
1613 chk->chunk_length = htons(4);
1614 }
1615 if (protlen >=
1616 (int)(sizeof(struct sctphdr) +
1617 2 * sizeof(struct sctp_chunkhdr))) {
1618 chk = chk + 1;
1619 chk->chunk_type = SCTP_PAD_CHUNK;
1620 chk->chunk_flags = 0;
1621 chk->chunk_length = htons(protlen -
1622 (sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr)));
1623 }
1624 }
1625 if (doipcksum) {
1626 sctp->checksum = sctp_crc32c(sctp, protlen);
1627 }
1628 }
1629
1630 int
sctp_check(const u_char * data,int seq)1631 sctp_check(const u_char *data, int seq)
1632 {
1633 struct sctphdr *const sctp = (struct sctphdr *) data;
1634
1635 if (ntohs(sctp->src_port) != ident ||
1636 ntohs(sctp->dest_port) != port + (fixedPort ? 0 : seq))
1637 return (0);
1638 if (protlen < (int)(sizeof(struct sctphdr) +
1639 sizeof(struct sctp_init_chunk))) {
1640 return (sctp->v_tag ==
1641 (u_int32_t)((sctp->src_port << 16) | sctp->dest_port));
1642 } else {
1643 /*
1644 * Don't verify the initiate_tag, since it is not available,
1645 * most of the time.
1646 */
1647 return (sctp->v_tag == 0);
1648 }
1649 }
1650 #endif
1651
1652 void
gre_prep(struct outdata * outdata)1653 gre_prep(struct outdata *outdata)
1654 {
1655 struct grehdr *const gre = (struct grehdr *) outp;
1656
1657 gre->flags = htons(0x2001);
1658 gre->proto = htons(port);
1659 gre->length = 0;
1660 gre->callId = htons(ident + outdata->seq);
1661 }
1662
1663 int
gre_check(const u_char * data,int seq)1664 gre_check(const u_char *data, int seq)
1665 {
1666 struct grehdr *const gre = (struct grehdr *) data;
1667
1668 return (ntohs(gre->proto) == port
1669 && ntohs(gre->callId) == ident + seq);
1670 }
1671
1672 void
gen_prep(struct outdata * outdata)1673 gen_prep(struct outdata *outdata)
1674 {
1675 u_int16_t *const ptr = (u_int16_t *) outp;
1676
1677 ptr[0] = htons(ident);
1678 ptr[1] = htons(port + outdata->seq);
1679 }
1680
1681 int
gen_check(const u_char * data,int seq)1682 gen_check(const u_char *data, int seq)
1683 {
1684 u_int16_t *const ptr = (u_int16_t *) data;
1685
1686 return (ntohs(ptr[0]) == ident
1687 && ntohs(ptr[1]) == port + seq);
1688 }
1689
1690 void
print(register u_char * buf,register int cc,register struct sockaddr_in * from)1691 print(register u_char *buf, register int cc, register struct sockaddr_in *from)
1692 {
1693 register struct ip *ip;
1694 register int hlen;
1695 char addr[INET_ADDRSTRLEN];
1696
1697 ip = (struct ip *) buf;
1698 hlen = ip->ip_hl << 2;
1699 cc -= hlen;
1700
1701 strlcpy(addr, inet_ntoa(from->sin_addr), sizeof(addr));
1702
1703 if (as_path)
1704 Printf(" [AS%u]", as_lookup(asn, addr, AF_INET));
1705
1706 if (nflag)
1707 Printf(" %s", addr);
1708 else
1709 Printf(" %s (%s)", inetname(from->sin_addr), addr);
1710
1711 if (verbose)
1712 Printf(" %d bytes to %s", cc, inet_ntoa(ip->ip_dst));
1713 }
1714
1715 /*
1716 * Checksum routine for UDP and TCP headers.
1717 */
1718 u_short
p_cksum(struct ip * ip,u_short * data,int len,int cov)1719 p_cksum(struct ip *ip, u_short *data, int len, int cov)
1720 {
1721 static struct ipovly ipo;
1722 u_short sum[2];
1723
1724 ipo.ih_pr = ip->ip_p;
1725 ipo.ih_len = htons(len);
1726 ipo.ih_src = ip->ip_src;
1727 ipo.ih_dst = ip->ip_dst;
1728
1729 sum[1] = in_cksum((u_short *)&ipo, sizeof(ipo)); /* pseudo ip hdr cksum */
1730 sum[0] = in_cksum(data, cov); /* payload data cksum */
1731
1732 return (~in_cksum(sum, sizeof(sum)));
1733 }
1734
1735 /*
1736 * Checksum routine for Internet Protocol family headers (C Version)
1737 */
1738 u_short
in_cksum(register u_short * addr,register int len)1739 in_cksum(register u_short *addr, register int len)
1740 {
1741 register int nleft = len;
1742 register u_short *w = addr;
1743 register u_short answer;
1744 register int sum = 0;
1745
1746 /*
1747 * Our algorithm is simple, using a 32 bit accumulator (sum),
1748 * we add sequential 16 bit words to it, and at the end, fold
1749 * back all the carry bits from the top 16 bits into the lower
1750 * 16 bits.
1751 */
1752 while (nleft > 1) {
1753 sum += *w++;
1754 nleft -= 2;
1755 }
1756
1757 /* mop up an odd byte, if necessary */
1758 if (nleft == 1)
1759 sum += *(u_char *)w;
1760
1761 /*
1762 * add back carry outs from top 16 bits to low 16 bits
1763 */
1764 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
1765 sum += (sum >> 16); /* add carry */
1766 answer = ~sum; /* truncate to 16 bits */
1767 return (answer);
1768 }
1769
1770 /*
1771 * CRC32C routine for the Stream Control Transmission Protocol
1772 */
1773
1774 #define CRC32C(c, d) (c = (c >> 8) ^ crc_c[(c ^ (d)) & 0xFF])
1775
1776 static u_int32_t crc_c[256] = {
1777 0x00000000, 0xF26B8303, 0xE13B70F7, 0x1350F3F4,
1778 0xC79A971F, 0x35F1141C, 0x26A1E7E8, 0xD4CA64EB,
1779 0x8AD958CF, 0x78B2DBCC, 0x6BE22838, 0x9989AB3B,
1780 0x4D43CFD0, 0xBF284CD3, 0xAC78BF27, 0x5E133C24,
1781 0x105EC76F, 0xE235446C, 0xF165B798, 0x030E349B,
1782 0xD7C45070, 0x25AFD373, 0x36FF2087, 0xC494A384,
1783 0x9A879FA0, 0x68EC1CA3, 0x7BBCEF57, 0x89D76C54,
1784 0x5D1D08BF, 0xAF768BBC, 0xBC267848, 0x4E4DFB4B,
1785 0x20BD8EDE, 0xD2D60DDD, 0xC186FE29, 0x33ED7D2A,
1786 0xE72719C1, 0x154C9AC2, 0x061C6936, 0xF477EA35,
1787 0xAA64D611, 0x580F5512, 0x4B5FA6E6, 0xB93425E5,
1788 0x6DFE410E, 0x9F95C20D, 0x8CC531F9, 0x7EAEB2FA,
1789 0x30E349B1, 0xC288CAB2, 0xD1D83946, 0x23B3BA45,
1790 0xF779DEAE, 0x05125DAD, 0x1642AE59, 0xE4292D5A,
1791 0xBA3A117E, 0x4851927D, 0x5B016189, 0xA96AE28A,
1792 0x7DA08661, 0x8FCB0562, 0x9C9BF696, 0x6EF07595,
1793 0x417B1DBC, 0xB3109EBF, 0xA0406D4B, 0x522BEE48,
1794 0x86E18AA3, 0x748A09A0, 0x67DAFA54, 0x95B17957,
1795 0xCBA24573, 0x39C9C670, 0x2A993584, 0xD8F2B687,
1796 0x0C38D26C, 0xFE53516F, 0xED03A29B, 0x1F682198,
1797 0x5125DAD3, 0xA34E59D0, 0xB01EAA24, 0x42752927,
1798 0x96BF4DCC, 0x64D4CECF, 0x77843D3B, 0x85EFBE38,
1799 0xDBFC821C, 0x2997011F, 0x3AC7F2EB, 0xC8AC71E8,
1800 0x1C661503, 0xEE0D9600, 0xFD5D65F4, 0x0F36E6F7,
1801 0x61C69362, 0x93AD1061, 0x80FDE395, 0x72966096,
1802 0xA65C047D, 0x5437877E, 0x4767748A, 0xB50CF789,
1803 0xEB1FCBAD, 0x197448AE, 0x0A24BB5A, 0xF84F3859,
1804 0x2C855CB2, 0xDEEEDFB1, 0xCDBE2C45, 0x3FD5AF46,
1805 0x7198540D, 0x83F3D70E, 0x90A324FA, 0x62C8A7F9,
1806 0xB602C312, 0x44694011, 0x5739B3E5, 0xA55230E6,
1807 0xFB410CC2, 0x092A8FC1, 0x1A7A7C35, 0xE811FF36,
1808 0x3CDB9BDD, 0xCEB018DE, 0xDDE0EB2A, 0x2F8B6829,
1809 0x82F63B78, 0x709DB87B, 0x63CD4B8F, 0x91A6C88C,
1810 0x456CAC67, 0xB7072F64, 0xA457DC90, 0x563C5F93,
1811 0x082F63B7, 0xFA44E0B4, 0xE9141340, 0x1B7F9043,
1812 0xCFB5F4A8, 0x3DDE77AB, 0x2E8E845F, 0xDCE5075C,
1813 0x92A8FC17, 0x60C37F14, 0x73938CE0, 0x81F80FE3,
1814 0x55326B08, 0xA759E80B, 0xB4091BFF, 0x466298FC,
1815 0x1871A4D8, 0xEA1A27DB, 0xF94AD42F, 0x0B21572C,
1816 0xDFEB33C7, 0x2D80B0C4, 0x3ED04330, 0xCCBBC033,
1817 0xA24BB5A6, 0x502036A5, 0x4370C551, 0xB11B4652,
1818 0x65D122B9, 0x97BAA1BA, 0x84EA524E, 0x7681D14D,
1819 0x2892ED69, 0xDAF96E6A, 0xC9A99D9E, 0x3BC21E9D,
1820 0xEF087A76, 0x1D63F975, 0x0E330A81, 0xFC588982,
1821 0xB21572C9, 0x407EF1CA, 0x532E023E, 0xA145813D,
1822 0x758FE5D6, 0x87E466D5, 0x94B49521, 0x66DF1622,
1823 0x38CC2A06, 0xCAA7A905, 0xD9F75AF1, 0x2B9CD9F2,
1824 0xFF56BD19, 0x0D3D3E1A, 0x1E6DCDEE, 0xEC064EED,
1825 0xC38D26C4, 0x31E6A5C7, 0x22B65633, 0xD0DDD530,
1826 0x0417B1DB, 0xF67C32D8, 0xE52CC12C, 0x1747422F,
1827 0x49547E0B, 0xBB3FFD08, 0xA86F0EFC, 0x5A048DFF,
1828 0x8ECEE914, 0x7CA56A17, 0x6FF599E3, 0x9D9E1AE0,
1829 0xD3D3E1AB, 0x21B862A8, 0x32E8915C, 0xC083125F,
1830 0x144976B4, 0xE622F5B7, 0xF5720643, 0x07198540,
1831 0x590AB964, 0xAB613A67, 0xB831C993, 0x4A5A4A90,
1832 0x9E902E7B, 0x6CFBAD78, 0x7FAB5E8C, 0x8DC0DD8F,
1833 0xE330A81A, 0x115B2B19, 0x020BD8ED, 0xF0605BEE,
1834 0x24AA3F05, 0xD6C1BC06, 0xC5914FF2, 0x37FACCF1,
1835 0x69E9F0D5, 0x9B8273D6, 0x88D28022, 0x7AB90321,
1836 0xAE7367CA, 0x5C18E4C9, 0x4F48173D, 0xBD23943E,
1837 0xF36E6F75, 0x0105EC76, 0x12551F82, 0xE03E9C81,
1838 0x34F4F86A, 0xC69F7B69, 0xD5CF889D, 0x27A40B9E,
1839 0x79B737BA, 0x8BDCB4B9, 0x988C474D, 0x6AE7C44E,
1840 0xBE2DA0A5, 0x4C4623A6, 0x5F16D052, 0xAD7D5351
1841 };
1842
1843 u_int32_t
sctp_crc32c(const void * packet,u_int32_t len)1844 sctp_crc32c(const void *packet, u_int32_t len)
1845 {
1846 u_int32_t i, crc32c;
1847 u_int8_t byte0, byte1, byte2, byte3;
1848 const u_int8_t *buf = (const u_int8_t *)packet;
1849
1850 crc32c = ~0;
1851 for (i = 0; i < len; i++)
1852 CRC32C(crc32c, buf[i]);
1853 crc32c = ~crc32c;
1854 byte0 = crc32c & 0xff;
1855 byte1 = (crc32c >> 8) & 0xff;
1856 byte2 = (crc32c >> 16) & 0xff;
1857 byte3 = (crc32c >> 24) & 0xff;
1858 crc32c = ((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3);
1859 return (htonl(crc32c));
1860 }
1861
1862 /*
1863 * Subtract 2 timeval structs: out = out - in.
1864 * Out is assumed to be within about LONG_MAX seconds of in.
1865 */
1866 void
tvsub(register struct timeval * out,register struct timeval * in)1867 tvsub(register struct timeval *out, register struct timeval *in)
1868 {
1869
1870 if ((out->tv_usec -= in->tv_usec) < 0) {
1871 --out->tv_sec;
1872 out->tv_usec += 1000000;
1873 }
1874 out->tv_sec -= in->tv_sec;
1875 }
1876
1877 /*
1878 * Construct an Internet address representation.
1879 * If the nflag has been supplied, give
1880 * numeric value, otherwise try for symbolic name.
1881 */
1882 char *
inetname(struct in_addr in)1883 inetname(struct in_addr in)
1884 {
1885 register char *cp;
1886 register struct hostent *hp;
1887 static int first = 1;
1888 static char domain[MAXHOSTNAMELEN + 1], line[MAXHOSTNAMELEN + 1];
1889
1890 if (first && !nflag) {
1891 first = 0;
1892 if (gethostname(domain, sizeof(domain) - 1) < 0)
1893 domain[0] = '\0';
1894 else {
1895 cp = strchr(domain, '.');
1896 if (cp == NULL) {
1897 #ifdef WITH_CASPER
1898 if (capdns != NULL)
1899 hp = cap_gethostbyname(capdns, domain);
1900 else
1901 #endif
1902 hp = gethostbyname(domain);
1903 if (hp != NULL)
1904 cp = strchr(hp->h_name, '.');
1905 }
1906 if (cp == NULL)
1907 domain[0] = '\0';
1908 else {
1909 ++cp;
1910 (void)strncpy(domain, cp, sizeof(domain) - 1);
1911 domain[sizeof(domain) - 1] = '\0';
1912 }
1913 }
1914 }
1915 if (!nflag && in.s_addr != INADDR_ANY) {
1916 #ifdef WITH_CASPER
1917 if (capdns != NULL)
1918 hp = cap_gethostbyaddr(capdns, (char *)&in, sizeof(in),
1919 AF_INET);
1920 else
1921 #endif
1922 hp = gethostbyaddr((char *)&in, sizeof(in), AF_INET);
1923 if (hp != NULL) {
1924 if ((cp = strchr(hp->h_name, '.')) != NULL &&
1925 strcmp(cp + 1, domain) == 0)
1926 *cp = '\0';
1927 (void)strncpy(line, hp->h_name, sizeof(line) - 1);
1928 line[sizeof(line) - 1] = '\0';
1929 return (line);
1930 }
1931 }
1932 return (inet_ntoa(in));
1933 }
1934
1935 struct hostinfo *
gethostinfo(register char * hostname)1936 gethostinfo(register char *hostname)
1937 {
1938 register int n;
1939 register struct hostent *hp;
1940 register struct hostinfo *hi;
1941 register char **p;
1942 register u_int32_t addr, *ap;
1943
1944 if (strlen(hostname) >= MAXHOSTNAMELEN) {
1945 Fprintf(stderr, "%s: hostname \"%.32s...\" is too long\n",
1946 prog, hostname);
1947 exit(1);
1948 }
1949 hi = calloc(1, sizeof(*hi));
1950 if (hi == NULL) {
1951 Fprintf(stderr, "%s: calloc %s\n", prog, strerror(errno));
1952 exit(1);
1953 }
1954 addr = inet_addr(hostname);
1955 if ((int32_t)addr != -1) {
1956 hi->name = strdup(hostname);
1957 hi->n = 1;
1958 hi->addrs = calloc(1, sizeof(hi->addrs[0]));
1959 if (hi->addrs == NULL) {
1960 Fprintf(stderr, "%s: calloc %s\n",
1961 prog, strerror(errno));
1962 exit(1);
1963 }
1964 hi->addrs[0] = addr;
1965 return (hi);
1966 }
1967
1968 #ifdef WITH_CASPER
1969 if (capdns != NULL)
1970 hp = cap_gethostbyname(capdns, hostname);
1971 else
1972 #endif
1973 hp = gethostbyname(hostname);
1974 if (hp == NULL) {
1975 Fprintf(stderr, "%s: unknown host %s\n", prog, hostname);
1976 exit(1);
1977 }
1978 if (hp->h_addrtype != AF_INET || hp->h_length != 4) {
1979 Fprintf(stderr, "%s: bad host %s\n", prog, hostname);
1980 exit(1);
1981 }
1982 hi->name = strdup(hp->h_name);
1983 for (n = 0, p = hp->h_addr_list; *p != NULL; ++n, ++p)
1984 continue;
1985 hi->n = n;
1986 hi->addrs = calloc(n, sizeof(hi->addrs[0]));
1987 if (hi->addrs == NULL) {
1988 Fprintf(stderr, "%s: calloc %s\n", prog, strerror(errno));
1989 exit(1);
1990 }
1991 for (ap = hi->addrs, p = hp->h_addr_list; *p != NULL; ++ap, ++p)
1992 memcpy(ap, *p, sizeof(*ap));
1993 return (hi);
1994 }
1995
1996 void
freehostinfo(register struct hostinfo * hi)1997 freehostinfo(register struct hostinfo *hi)
1998 {
1999 if (hi->name != NULL) {
2000 free(hi->name);
2001 hi->name = NULL;
2002 }
2003 free((char *)hi->addrs);
2004 free((char *)hi);
2005 }
2006
2007 void
getaddr(register u_int32_t * ap,register char * hostname)2008 getaddr(register u_int32_t *ap, register char *hostname)
2009 {
2010 register struct hostinfo *hi;
2011
2012 hi = gethostinfo(hostname);
2013 *ap = hi->addrs[0];
2014 freehostinfo(hi);
2015 }
2016
2017 void
setsin(register struct sockaddr_in * sin,register u_int32_t addr)2018 setsin(register struct sockaddr_in *sin, register u_int32_t addr)
2019 {
2020
2021 memset(sin, 0, sizeof(*sin));
2022 sin->sin_len = sizeof(*sin);
2023 sin->sin_family = AF_INET;
2024 sin->sin_addr.s_addr = addr;
2025 }
2026
2027 /* String to value with optional min and max. Handles decimal and hex. */
2028 int
str2val(register const char * str,register const char * what,register int mi,register int ma)2029 str2val(register const char *str, register const char *what,
2030 register int mi, register int ma)
2031 {
2032 register const char *cp;
2033 register int val;
2034 char *ep;
2035
2036 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
2037 cp = str + 2;
2038 val = (int)strtol(cp, &ep, 16);
2039 } else
2040 val = (int)strtol(str, &ep, 10);
2041 if (*ep != '\0') {
2042 Fprintf(stderr, "%s: \"%s\" bad value for %s\n",
2043 prog, str, what);
2044 exit(1);
2045 }
2046 if (val < mi && mi >= 0) {
2047 if (mi == 0)
2048 Fprintf(stderr, "%s: %s must be >= %d\n",
2049 prog, what, mi);
2050 else
2051 Fprintf(stderr, "%s: %s must be > %d\n",
2052 prog, what, mi - 1);
2053 exit(1);
2054 }
2055 if (val > ma && ma >= 0) {
2056 Fprintf(stderr, "%s: %s must be <= %d\n", prog, what, ma);
2057 exit(1);
2058 }
2059 return (val);
2060 }
2061
2062 struct outproto *
setproto(char * pname)2063 setproto(char *pname)
2064 {
2065 struct outproto *proto;
2066 int i;
2067
2068 for (i = 0; protos[i].name != NULL; i++) {
2069 if (strcasecmp(protos[i].name, pname) == 0) {
2070 break;
2071 }
2072 }
2073 proto = &protos[i];
2074 if (proto->name == NULL) { /* generic handler */
2075 struct protoent *pe;
2076 u_long pnum;
2077
2078 /* Determine the IP protocol number */
2079 if ((pe = getprotobyname(pname)) != NULL)
2080 pnum = pe->p_proto;
2081 else
2082 pnum = str2val(optarg, "proto number", 1, 255);
2083 proto->num = pnum;
2084 }
2085 return (proto);
2086 }
2087
2088 void
pkt_compare(const u_char * a,int la,const u_char * b,int lb)2089 pkt_compare(const u_char *a, int la, const u_char *b, int lb) {
2090 int l;
2091 int i;
2092
2093 for (i = 0; i < la; i++)
2094 Printf("%02x", (unsigned int)a[i]);
2095 Printf("\n");
2096 l = (la <= lb) ? la : lb;
2097 for (i = 0; i < l; i++)
2098 if (a[i] == b[i])
2099 Printf("__");
2100 else
2101 Printf("%02x", (unsigned int)b[i]);
2102 for (; i < lb; i++)
2103 Printf("%02x", (unsigned int)b[i]);
2104 Printf("\n");
2105 }
2106
2107
2108 void
usage(void)2109 usage(void)
2110 {
2111 Fprintf(stderr,
2112 "Usage: %s [-adDeEFInrSvx] [-A as_server] [-f first_ttl] [-g gateway]\n"
2113 "\t[-i iface] [-m max_ttl] [-M first_ttl] [-p port] [-P proto]\n"
2114 "\t[-q nprobes] [-s src_addr] [-t tos] [-w waittime]\n"
2115 "\t[-z pausemsecs] host [packetlen]\n", prog);
2116 exit(1);
2117 }
2118