Call WSAStartup and WSACleanup.
[reactos.git] / reactos / apps / utils / net / tracert / tracert.c
1 /*-
2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Van Jacobson.
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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 #ifndef lint
38 static char copyright[] =
39 "@(#) Copyright (c) 1990, 1993\n\
40 The Regents of the University of California. All rights reserved.\n";
41 #endif /* not lint */
42
43 #ifndef lint
44 static char sccsid[] = "@(#)traceroute.c 8.1 (Berkeley) 6/6/93";
45 #endif /* not lint */
46
47 /*
48 * traceroute host - trace the route ip packets follow going to "host".
49 *
50 * Attempt to trace the route an ip packet would follow to some
51 * internet host. We find out intermediate hops by launching probe
52 * packets with a small ttl (time to live) then listening for an
53 * icmp "time exceeded" reply from a gateway. We start our probes
54 * with a ttl of one and increase by one until we get an icmp "port
55 * unreachable" (which means we got to "host") or hit a max (which
56 * defaults to 30 hops & can be changed with the -m flag). Three
57 * probes (change with -q flag) are sent at each ttl setting and a
58 * line is printed showing the ttl, address of the gateway and
59 * round trip time of each probe. If the probe answers come from
60 * different gateways, the address of each responding system will
61 * be printed. If there is no response within a 5 sec. timeout
62 * interval (changed with the -w flag), a "*" is printed for that
63 * probe.
64 *
65 * Probe packets are UDP format. We don't want the destination
66 * host to process them so the destination port is set to an
67 * unlikely value (if some clod on the destination is using that
68 * value, it can be changed with the -p flag).
69 *
70 * A sample use might be:
71 *
72 * [yak 71]% traceroute nis.nsf.net.
73 * traceroute to nis.nsf.net (35.1.1.48), 30 hops max, 56 byte packet
74 * 1 helios.ee.lbl.gov (128.3.112.1) 19 ms 19 ms 0 ms
75 * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
76 * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 39 ms 19 ms
77 * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 39 ms
78 * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 39 ms 39 ms 39 ms
79 * 6 128.32.197.4 (128.32.197.4) 40 ms 59 ms 59 ms
80 * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 59 ms
81 * 8 129.140.70.13 (129.140.70.13) 99 ms 99 ms 80 ms
82 * 9 129.140.71.6 (129.140.71.6) 139 ms 239 ms 319 ms
83 * 10 129.140.81.7 (129.140.81.7) 220 ms 199 ms 199 ms
84 * 11 nic.merit.edu (35.1.1.48) 239 ms 239 ms 239 ms
85 *
86 * Note that lines 2 & 3 are the same. This is due to a buggy
87 * kernel on the 2nd hop system -- lbl-csam.arpa -- that forwards
88 * packets with a zero ttl.
89 *
90 * A more interesting example is:
91 *
92 * [yak 72]% traceroute allspice.lcs.mit.edu.
93 * traceroute to allspice.lcs.mit.edu (18.26.0.115), 30 hops max
94 * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
95 * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 19 ms 19 ms
96 * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 19 ms
97 * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 19 ms 39 ms 39 ms
98 * 5 ccn-nerif22.Berkeley.EDU (128.32.168.22) 20 ms 39 ms 39 ms
99 * 6 128.32.197.4 (128.32.197.4) 59 ms 119 ms 39 ms
100 * 7 131.119.2.5 (131.119.2.5) 59 ms 59 ms 39 ms
101 * 8 129.140.70.13 (129.140.70.13) 80 ms 79 ms 99 ms
102 * 9 129.140.71.6 (129.140.71.6) 139 ms 139 ms 159 ms
103 * 10 129.140.81.7 (129.140.81.7) 199 ms 180 ms 300 ms
104 * 11 129.140.72.17 (129.140.72.17) 300 ms 239 ms 239 ms
105 * 12 * * *
106 * 13 128.121.54.72 (128.121.54.72) 259 ms 499 ms 279 ms
107 * 14 * * *
108 * 15 * * *
109 * 16 * * *
110 * 17 * * *
111 * 18 ALLSPICE.LCS.MIT.EDU (18.26.0.115) 339 ms 279 ms 279 ms
112 *
113 * (I start to see why I'm having so much trouble with mail to
114 * MIT.) Note that the gateways 12, 14, 15, 16 & 17 hops away
115 * either don't send ICMP "time exceeded" messages or send them
116 * with a ttl too small to reach us. 14 - 17 are running the
117 * MIT C Gateway code that doesn't send "time exceeded"s. God
118 * only knows what's going on with 12.
119 *
120 * The silent gateway 12 in the above may be the result of a bug in
121 * the 4.[23]BSD network code (and its derivatives): 4.x (x <= 3)
122 * sends an unreachable message using whatever ttl remains in the
123 * original datagram. Since, for gateways, the remaining ttl is
124 * zero, the icmp "time exceeded" is guaranteed to not make it back
125 * to us. The behavior of this bug is slightly more interesting
126 * when it appears on the destination system:
127 *
128 * 1 helios.ee.lbl.gov (128.3.112.1) 0 ms 0 ms 0 ms
129 * 2 lilac-dmc.Berkeley.EDU (128.32.216.1) 39 ms 19 ms 39 ms
130 * 3 lilac-dmc.Berkeley.EDU (128.32.216.1) 19 ms 39 ms 19 ms
131 * 4 ccngw-ner-cc.Berkeley.EDU (128.32.136.23) 39 ms 40 ms 19 ms
132 * 5 ccn-nerif35.Berkeley.EDU (128.32.168.35) 39 ms 39 ms 39 ms
133 * 6 csgw.Berkeley.EDU (128.32.133.254) 39 ms 59 ms 39 ms
134 * 7 * * *
135 * 8 * * *
136 * 9 * * *
137 * 10 * * *
138 * 11 * * *
139 * 12 * * *
140 * 13 rip.Berkeley.EDU (128.32.131.22) 59 ms ! 39 ms ! 39 ms !
141 *
142 * Notice that there are 12 "gateways" (13 is the final
143 * destination) and exactly the last half of them are "missing".
144 * What's really happening is that rip (a Sun-3 running Sun OS3.5)
145 * is using the ttl from our arriving datagram as the ttl in its
146 * icmp reply. So, the reply will time out on the return path
147 * (with no notice sent to anyone since icmp's aren't sent for
148 * icmp's) until we probe with a ttl that's at least twice the path
149 * length. I.e., rip is really only 7 hops away. A reply that
150 * returns with a ttl of 1 is a clue this problem exists.
151 * Traceroute prints a "!" after the time if the ttl is <= 1.
152 * Since vendors ship a lot of obsolete (DEC's Ultrix, Sun 3.x) or
153 * non-standard (HPUX) software, expect to see this problem
154 * frequently and/or take care picking the target host of your
155 * probes.
156 *
157 * Other possible annotations after the time are !H, !N, !P (got a host,
158 * network or protocol unreachable, respectively), !S or !F (source
159 * route failed or fragmentation needed -- neither of these should
160 * ever occur and the associated gateway is busted if you see one). If
161 * almost all the probes result in some kind of unreachable, traceroute
162 * will give up and exit.
163 *
164 * Notes
165 * -----
166 * This program must be run by root or be setuid. (I suggest that
167 * you *don't* make it setuid -- casual use could result in a lot
168 * of unnecessary traffic on our poor, congested nets.)
169 *
170 * This program requires a kernel mod that does not appear in any
171 * system available from Berkeley: A raw ip socket using proto
172 * IPPROTO_RAW must interpret the data sent as an ip datagram (as
173 * opposed to data to be wrapped in a ip datagram). See the README
174 * file that came with the source to this program for a description
175 * of the mods I made to /sys/netinet/raw_ip.c. Your mileage may
176 * vary. But, again, ANY 4.x (x < 4) BSD KERNEL WILL HAVE TO BE
177 * MODIFIED TO RUN THIS PROGRAM.
178 *
179 * The udp port usage may appear bizarre (well, ok, it is bizarre).
180 * The problem is that an icmp message only contains 8 bytes of
181 * data from the original datagram. 8 bytes is the size of a udp
182 * header so, if we want to associate replies with the original
183 * datagram, the necessary information must be encoded into the
184 * udp header (the ip id could be used but there's no way to
185 * interlock with the kernel's assignment of ip id's and, anyway,
186 * it would have taken a lot more kernel hacking to allow this
187 * code to set the ip id). So, to allow two or more users to
188 * use traceroute simultaneously, we use this task's pid as the
189 * source port (the high bit is set to move the port number out
190 * of the "likely" range). To keep track of which probe is being
191 * replied to (so times and/or hop counts don't get confused by a
192 * reply that was delayed in transit), we increment the destination
193 * port number before each probe.
194 *
195 * Don't use this as a coding example. I was trying to find a
196 * routing problem and this code sort-of popped out after 48 hours
197 * without sleep. I was amazed it ever compiled, much less ran.
198 *
199 * I stole the idea for this program from Steve Deering. Since
200 * the first release, I've learned that had I attended the right
201 * IETF working group meetings, I also could have stolen it from Guy
202 * Almes or Matt Mathis. I don't know (or care) who came up with
203 * the idea first. I envy the originators' perspicacity and I'm
204 * glad they didn't keep the idea a secret.
205 *
206 * Tim Seaver, Ken Adelman and C. Philip Wood provided bug fixes and/or
207 * enhancements to the original distribution.
208 *
209 * I've hacked up a round-trip-route version of this that works by
210 * sending a loose-source-routed udp datagram through the destination
211 * back to yourself. Unfortunately, SO many gateways botch source
212 * routing, the thing is almost worthless. Maybe one day...
213 *
214 * -- Van Jacobson (van@helios.ee.lbl.gov)
215 * Tue Dec 20 03:50:13 PST 1988
216 */
217
218 #define caddr_t void *
219
220 #include <stdio.h>
221 #include <errno.h>
222 #include <stdlib.h>
223 #include <string.h>
224 #include <unistd.h>
225
226 #include <winsock2.h>
227
228
229 #include <stdio.h>
230 #include <time.h>
231 #include <winsock.h>
232
233 //void print(buf, cc, from);
234 char * inetname(in);
235 double deltaT(t1p, t2p);
236 void usage();
237 void send_probe(seq, ttl);
238
239 #define bzero( ptr, count ) memset( ptr, 0, count )
240 #define bcopy(src,dest,len) memcpy(dest,src,len)
241
242 // setlinebuf is equivalent to the setvbuf call below.
243 inline int setlinebuf(FILE *stream)
244 {
245 return setvbuf( stream, (char*)0, _IONBF, 0 );
246 }
247
248 #ifndef __GNUC__
249 #define EPOCHFILETIME (116444736000000000i64)
250 #else
251 #define EPOCHFILETIME (116444736000000000LL)
252 #endif
253
254 struct timezone {
255 int tz_minuteswest; /* minutes W of Greenwich */
256 int tz_dsttime; /* type of dst correction */
257 };
258
259 int gettimeofday(struct timeval *tv, struct timezone *tz)
260 {
261 FILETIME ft;
262 LARGE_INTEGER li;
263 __int64 t;
264 static int tzflag;
265
266 if (tv)
267 {
268 GetSystemTimeAsFileTime(&ft);
269 //li.LowPart = ft.dwLowDateTime;
270 //li.HighPart = ft.dwHighDateTime;
271 t = li.QuadPart; /* In 100-nanosecond intervals */
272 t -= EPOCHFILETIME; /* Offset to the Epoch time */
273 t /= 10; /* In microseconds */
274 tv->tv_sec = (long)(t / 1000000);
275 tv->tv_usec = (long)(t % 1000000);
276 }
277
278 if (tz)
279 {
280 if (!tzflag)
281 {
282 _tzset();
283 tzflag++;
284 }
285 tz->tz_minuteswest = _timezone / 60;
286 tz->tz_dsttime = _daylight;
287 }
288
289 return 0;
290 }
291
292
293
294 /* Set up endiannes macros for the ip and ip_icmp BSD headers */
295 #ifndef BIG_ENDIAN
296 #define BIG_ENDIAN 4321
297 #endif
298 #ifndef LITTLE_ENDIAN
299 #define LITTLE_ENDIAN 1234
300 #endif
301 #ifndef BYTE_ORDER
302 #ifdef WORDS_BIGENDIAN
303 #define BYTE_ORDER BIG_ENDIAN
304 #else
305 #define BYTE_ORDER LITTLE_ENDIAN
306 #endif
307 #endif /* BYTE_ORDER */
308
309 #define u_int16_t WORD
310 #define u_int32_t DWORD
311
312 /* These are BSD headers. We use these here because they are needed on
313 * libc5 Linux systems. On other platforms they are usually simply more
314 * complete than the native stuff, and cause less portability problems
315 * so we use them anyway.
316 */
317 #include "ip.h"
318 #include "ip_icmp.h"
319
320
321 #define MAXPACKET 65535 /* max ip packet size */
322 #ifndef MAXHOSTNAMELEN
323 #define MAXHOSTNAMELEN 64
324 #endif
325
326 #ifndef FD_SET
327 #define NFDBITS (8*sizeof(fd_set))
328 #define FD_SETSIZE NFDBITS
329 #define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
330 #define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
331 #define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
332 #define FD_ZERO(p) bzero((char *)(p), sizeof(*(p)))
333 #endif
334
335 #define Fprintf (void)fprintf
336 #define Sprintf (void)sprintf
337 #define Printf (void)printf
338
339 // Define the UDP header
340 //
341 typedef struct udp_hdr
342 {
343 unsigned short src_portno; // Source port number
344 unsigned short dst_portno; // Destination port number
345 unsigned short udp_length; // UDP packet length
346 unsigned short udp_checksum; // UDP checksum (optional)
347 } UDP_HDR, *PUDP_HDR;
348
349 /*
350 * format of a (udp) probe packet.
351 */
352 struct opacket {
353 struct ip ip;
354 UDP_HDR udp;
355 u_char seq; /* sequence number of this packet */
356 u_char ttl; /* ttl packet left with */
357 struct timeval tv; /* time packet left */
358 };
359
360 u_char packet[512]; /* last inbound (icmp) packet */
361 struct opacket *outpacket; /* last output (udp) packet */
362
363 #if 0
364 int wait_for_reply __P((int, struct sockaddr_in *));
365 void send_probe __P((int, int));
366 double deltaT __P((struct timeval *, struct timeval *));
367 int packet_ok __P((u_char *, int, struct sockaddr_in *, int));
368 //void print __P((u_char *, int, struct sockaddr_in *));
369 void tvsub __P((struct timeval *, struct timeval *));
370 char *inetname __P((struct in_addr));
371 void usage __P(());
372 #endif
373
374 int s; /* receive (icmp) socket file descriptor */
375 int sndsock; /* send (udp) socket file descriptor */
376 struct timezone tz; /* leftover */
377
378 struct sockaddr whereto; /* Who to try to reach */
379 int datalen; /* How much data */
380
381 char *source = 0;
382 char *hostname;
383
384 int nprobes = 3;
385 int max_ttl = 30;
386 u_short ident;
387 u_short port = 32768+666; /* start udp dest port # for probe packets */
388 int options; /* socket options */
389 int verbose;
390 int waittime = 5; /* time to wait for response (in seconds) */
391 int nflag; /* print addresses numerically */
392
393 void
394 print(buf, cc, from)
395 u_char *buf;
396 int cc;
397 struct sockaddr_in *from;
398 {
399 struct ip *ip;
400 int hlen;
401
402 ip = (struct ip *) buf;
403 hlen = ip->ip_hl << 2;
404 cc -= hlen;
405
406 if (nflag)
407 Printf(" %s", inet_ntoa(from->sin_addr));
408 else
409 Printf(" %s (%s)", inetname(from->sin_addr),
410 inet_ntoa(from->sin_addr));
411
412 if (verbose)
413 Printf (" %d bytes to %s", cc, inet_ntoa (ip->ip_dst));
414 }
415
416
417 int
418 main(argc, argv)
419 int argc;
420 char *argv[];
421 {
422 extern char *optarg;
423 extern int optind;
424 struct hostent *hp;
425 struct protoent *pe;
426 struct sockaddr_in from, *to;
427 int ch, i, on, probe, seq, tos, ttl;
428 WSADATA wsadata;
429 INT status;
430
431 status = WSAStartup(MAKEWORD(2, 2), &wsadata);
432 if (status != 0) {
433 printf("Could not initialize winsock dll.\n");
434 return FALSE;
435 }
436
437 on = 1;
438 seq = tos = 0;
439 to = (struct sockaddr_in *)&whereto;
440 while ((ch = getopt(argc, argv, "dm:np:q:rs:t:w:v")) != EOF)
441 switch(ch) {
442 case 'd':
443 options |= SO_DEBUG;
444 break;
445 case 'm':
446 max_ttl = atoi(optarg);
447 if (max_ttl <= 1) {
448 Fprintf(stderr,
449 "traceroute: max ttl must be >1.\n");
450 WSACleanup();
451 exit(1);
452 }
453 break;
454 case 'n':
455 nflag++;
456 break;
457 case 'p':
458 port = atoi(optarg);
459 if (port < 1) {
460 Fprintf(stderr,
461 "traceroute: port must be >0.\n");
462 WSACleanup();
463 exit(1);
464 }
465 break;
466 case 'q':
467 nprobes = atoi(optarg);
468 if (nprobes < 1) {
469 Fprintf(stderr,
470 "traceroute: nprobes must be >0.\n");
471 WSACleanup();
472 exit(1);
473 }
474 break;
475 case 'r':
476 options |= SO_DONTROUTE;
477 break;
478 case 's':
479 /*
480 * set the ip source address of the outbound
481 * probe (e.g., on a multi-homed host).
482 */
483 source = optarg;
484 break;
485 case 't':
486 tos = atoi(optarg);
487 if (tos < 0 || tos > 255) {
488 Fprintf(stderr,
489 "traceroute: tos must be 0 to 255.\n");
490 WSACleanup();
491 exit(1);
492 }
493 break;
494 case 'v':
495 verbose++;
496 break;
497 case 'w':
498 waittime = atoi(optarg);
499 if (waittime <= 1) {
500 Fprintf(stderr,
501 "traceroute: wait must be >1 sec.\n");
502 WSACleanup();
503 exit(1);
504 }
505 break;
506 default:
507 usage();
508 }
509 argc -= optind;
510 argv += optind;
511
512 if (argc < 1)
513 usage();
514
515 setlinebuf (stdout);
516
517 (void) bzero((char *)&whereto, sizeof(struct sockaddr));
518 to->sin_family = AF_INET;
519 to->sin_addr.s_addr = inet_addr(*argv);
520 if (to->sin_addr.s_addr != -1)
521 hostname = *argv;
522 else {
523 hp = gethostbyname(*argv);
524 if (hp) {
525 to->sin_family = hp->h_addrtype;
526 bcopy(hp->h_addr, (caddr_t)&to->sin_addr, hp->h_length);
527 hostname = hp->h_name;
528 } else {
529 (void)fprintf(stderr,
530 "traceroute: unknown host %s\n", *argv);
531 WSACleanup();
532 exit(1);
533 }
534 }
535 if (*++argv)
536 datalen = atoi(*argv);
537 if (datalen < 0 || datalen >= MAXPACKET - sizeof(struct opacket)) {
538 Fprintf(stderr,
539 "traceroute: packet size must be 0 <= s < %ld.\n",
540 MAXPACKET - sizeof(struct opacket));
541 WSACleanup();
542 exit(1);
543 }
544 datalen += sizeof(struct opacket);
545 outpacket = (struct opacket *)malloc((unsigned)datalen);
546 if (! outpacket) {
547 perror("traceroute: malloc");
548 WSACleanup();
549 exit(1);
550 }
551 (void) bzero((char *)outpacket, datalen);
552 outpacket->ip.ip_dst = to->sin_addr;
553 outpacket->ip.ip_tos = tos;
554 outpacket->ip.ip_v = IPVERSION;
555 outpacket->ip.ip_id = 0;
556
557 ident = (getpid() & 0xffff) | 0x8000;
558
559 if ((pe = getprotobyname("icmp")) == NULL) {
560 Fprintf(stderr, "icmp: unknown protocol\n");
561 WSACleanup();
562 exit(10);
563 }
564 if ((s = socket(AF_INET, SOCK_RAW, pe->p_proto)) < 0) {
565 perror("traceroute: icmp socket");
566 WSACleanup();
567 exit(5);
568 }
569 if (options & SO_DEBUG)
570 (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
571 (char *)&on, sizeof(on));
572 if (options & SO_DONTROUTE)
573 (void) setsockopt(s, SOL_SOCKET, SO_DONTROUTE,
574 (char *)&on, sizeof(on));
575
576 if ((sndsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
577 perror("traceroute: raw socket");
578 WSACleanup();
579 exit(5);
580 }
581 #ifdef SO_SNDBUF
582 if (setsockopt(sndsock, SOL_SOCKET, SO_SNDBUF, (char *)&datalen,
583 sizeof(datalen)) < 0) {
584 perror("traceroute: SO_SNDBUF");
585 WSACleanup();
586 exit(6);
587 }
588 #endif /* SO_SNDBUF */
589 #ifdef IP_HDRINCL
590 if (setsockopt(sndsock, IPPROTO_IP, IP_HDRINCL, (char *)&on,
591 sizeof(on)) < 0) {
592 perror("traceroute: IP_HDRINCL");
593 WSACleanup();
594 exit(6);
595 }
596 #endif /* IP_HDRINCL */
597 if (options & SO_DEBUG)
598 (void) setsockopt(sndsock, SOL_SOCKET, SO_DEBUG,
599 (char *)&on, sizeof(on));
600 if (options & SO_DONTROUTE)
601 (void) setsockopt(sndsock, SOL_SOCKET, SO_DONTROUTE,
602 (char *)&on, sizeof(on));
603
604 if (source) {
605 (void) bzero((char *)&from, sizeof(struct sockaddr));
606 from.sin_family = AF_INET;
607 from.sin_addr.s_addr = inet_addr(source);
608 if (from.sin_addr.s_addr == -1) {
609 Printf("traceroute: unknown host %s\n", source);
610 WSACleanup();
611 exit(1);
612 }
613 outpacket->ip.ip_src = from.sin_addr;
614 #ifndef IP_HDRINCL
615 if (bind(sndsock, (struct sockaddr *)&from, sizeof(from)) < 0) {
616 perror ("traceroute: bind:");
617 WSACleanup();
618 exit (1);
619 }
620 #endif /* IP_HDRINCL */
621 }
622
623 Fprintf(stderr, "traceroute to %s (%s)", hostname,
624 inet_ntoa(to->sin_addr));
625 if (source)
626 Fprintf(stderr, " from %s", source);
627 Fprintf(stderr, ", %d hops max, %d byte packets\n", max_ttl, datalen);
628 (void) fflush(stderr);
629
630 for (ttl = 1; ttl <= max_ttl; ++ttl) {
631 u_long lastaddr = 0;
632 int got_there = 0;
633 int unreachable = 0;
634
635 Printf("%2d ", ttl);
636 for (probe = 0; probe < nprobes; ++probe) {
637 int cc;
638 struct timeval t1, t2;
639 struct timezone tz;
640 struct ip *ip;
641
642 (void) gettimeofday(&t1, &tz);
643 send_probe(++seq, ttl);
644 while (cc = wait_for_reply(s, &from)) {
645 (void) gettimeofday(&t2, &tz);
646 if ((i = packet_ok(packet, cc, &from, seq))) {
647 if (from.sin_addr.s_addr != lastaddr) {
648 print(packet, cc, &from);
649 lastaddr = from.sin_addr.s_addr;
650 }
651 Printf(" %g ms", deltaT(&t1, &t2));
652 switch(i - 1) {
653 case ICMP_UNREACH_PORT:
654 #ifndef ARCHAIC
655 ip = (struct ip *)packet;
656 if (ip->ip_ttl <= 1)
657 Printf(" !");
658 #endif /* ARCHAIC */
659 ++got_there;
660 break;
661 case ICMP_UNREACH_NET:
662 ++unreachable;
663 Printf(" !N");
664 break;
665 case ICMP_UNREACH_HOST:
666 ++unreachable;
667 Printf(" !H");
668 break;
669 case ICMP_UNREACH_PROTOCOL:
670 ++got_there;
671 Printf(" !P");
672 break;
673 case ICMP_UNREACH_NEEDFRAG:
674 ++unreachable;
675 Printf(" !F");
676 break;
677 case ICMP_UNREACH_SRCFAIL:
678 ++unreachable;
679 Printf(" !S");
680 break;
681 }
682 break;
683 }
684 }
685 if (cc == 0)
686 Printf(" *");
687 (void) fflush(stdout);
688 }
689 putchar('\n');
690 if (got_there || unreachable >= nprobes-1) {
691 WSACleanup();
692 exit(0);
693 }
694 }
695
696 WSACleanup();
697 return 0;
698 }
699
700 int
701 wait_for_reply(sock, from)
702 int sock;
703 struct sockaddr_in *from;
704 {
705 fd_set fds;
706 struct timeval wait;
707 int cc = 0;
708 int fromlen = sizeof (*from);
709
710 FD_ZERO(&fds);
711 FD_SET(sock, &fds);
712 wait.tv_sec = waittime; wait.tv_usec = 0;
713
714 if (select(sock+1, &fds, (fd_set *)0, (fd_set *)0, &wait) > 0)
715 cc=recvfrom(s, (char *)packet, sizeof(packet), 0,
716 (struct sockaddr *)from, &fromlen);
717
718 return(cc);
719 }
720
721
722 void
723 send_probe(seq, ttl)
724 int seq, ttl;
725 {
726 struct opacket *op = outpacket;
727 struct ip *ip = &op->ip;
728 struct udphdr *up = &op->udp;
729 int i;
730
731 ip->ip_off = 0;
732 ip->ip_hl = sizeof(*ip) >> 2;
733 ip->ip_p = IPPROTO_UDP;
734 ip->ip_len = datalen;
735 ip->ip_ttl = ttl;
736 ip->ip_v = IPVERSION;
737 ip->ip_id = htons(ident+seq);
738
739 // up->uh_sport = htons(ident);
740 // up->uh_dport = htons(port+seq);
741 // up->uh_ulen = htons((u_short)(datalen - sizeof(struct ip)));
742 // up->uh_sum = 0;
743
744 op->seq = seq;
745 op->ttl = ttl;
746 (void) gettimeofday(&op->tv, &tz);
747
748 i = sendto(sndsock, (char *)outpacket, datalen, 0, &whereto,
749 sizeof(struct sockaddr));
750 if (i < 0 || i != datalen) {
751 if (i<0)
752 perror("sendto");
753 Printf("traceroute: wrote %s %d chars, ret=%d\n", hostname,
754 datalen, i);
755 (void) fflush(stdout);
756 }
757 }
758
759
760 double
761 deltaT(t1p, t2p)
762 struct timeval *t1p, *t2p;
763 {
764 register double dt;
765
766 dt = (double)(t2p->tv_sec - t1p->tv_sec) * 1000.0 +
767 (double)(t2p->tv_usec - t1p->tv_usec) / 1000.0;
768 return (dt);
769 }
770
771
772 /*
773 * Convert an ICMP "type" field to a printable string.
774 */
775 char *
776 pr_type(t)
777 u_char t;
778 {
779 static char *ttab[] = {
780 "Echo Reply", "ICMP 1", "ICMP 2", "Dest Unreachable",
781 "Source Quench", "Redirect", "ICMP 6", "ICMP 7",
782 "Echo", "ICMP 9", "ICMP 10", "Time Exceeded",
783 "Param Problem", "Timestamp", "Timestamp Reply", "Info Request",
784 "Info Reply"
785 };
786
787 if(t > 16)
788 return("OUT-OF-RANGE");
789
790 return(ttab[t]);
791 }
792
793
794 int
795 packet_ok(buf, cc, from, seq)
796 u_char *buf;
797 int cc;
798 struct sockaddr_in *from;
799 int seq;
800 {
801 register struct icmp *icp;
802 u_char type, code;
803 int hlen;
804 #ifndef ARCHAIC
805 struct ip *ip;
806
807 ip = (struct ip *) buf;
808 hlen = ip->ip_hl << 2;
809 if (cc < hlen + ICMP_MINLEN) {
810 if (verbose)
811 Printf("packet too short (%d bytes) from %s\n", cc,
812 inet_ntoa(from->sin_addr));
813 return (0);
814 }
815 cc -= hlen;
816 icp = (struct icmp *)(buf + hlen);
817 #else
818 icp = (struct icmp *)buf;
819 #endif /* ARCHAIC */
820 type = icp->icmp_type; code = icp->icmp_code;
821 if ((type == ICMP_TIMXCEED && code == ICMP_TIMXCEED_INTRANS) ||
822 type == ICMP_UNREACH) {
823 struct ip *hip;
824 struct udphdr *up;
825
826 hip = &icp->icmp_ip;
827 hlen = hip->ip_hl << 2;
828 up = (struct udphdr *)((u_char *)hip + hlen);
829 // if (hlen + 12 <= cc && hip->ip_p == IPPROTO_UDP &&
830 // up->uh_sport == htons(ident) &&
831 // up->uh_dport == htons(port+seq))
832 if (hlen + 12 <= cc && hip->ip_p == IPPROTO_UDP)
833 return (type == ICMP_TIMXCEED? -1 : code+1);
834 }
835 #ifndef ARCHAIC
836 if (verbose) {
837 int i;
838 u_long *lp = (u_long *)&icp->icmp_ip;
839
840 Printf("\n%d bytes from %s to %s", cc,
841 inet_ntoa(from->sin_addr), inet_ntoa(ip->ip_dst));
842 Printf(": icmp type %d (%s) code %d\n", type, pr_type(type),
843 icp->icmp_code);
844 for (i = 4; i < cc ; i += sizeof(long))
845 Printf("%2d: x%8.8lx\n", i, *lp++);
846 }
847 #endif /* ARCHAIC */
848 return(0);
849 }
850
851 #ifdef notyet
852 /*
853 * Checksum routine for Internet Protocol family headers (C Version)
854 */
855 u_short
856 in_cksum(addr, len)
857 u_short *addr;
858 int len;
859 {
860 register int nleft = len;
861 register u_short *w = addr;
862 register u_short answer;
863 register int sum = 0;
864
865 /*
866 * Our algorithm is simple, using a 32 bit accumulator (sum),
867 * we add sequential 16 bit words to it, and at the end, fold
868 * back all the carry bits from the top 16 bits into the lower
869 * 16 bits.
870 */
871 while (nleft > 1) {
872 sum += *w++;
873 nleft -= 2;
874 }
875
876 /* mop up an odd byte, if necessary */
877 if (nleft == 1)
878 sum += *(u_char *)w;
879
880 /*
881 * add back carry outs from top 16 bits to low 16 bits
882 */
883 sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
884 sum += (sum >> 16); /* add carry */
885 answer = ~sum; /* truncate to 16 bits */
886 return (answer);
887 }
888 #endif /* notyet */
889
890 /*
891 * Subtract 2 timeval structs: out = out - in.
892 * Out is assumed to be >= in.
893 */
894 void
895 tvsub(out, in)
896 register struct timeval *out, *in;
897 {
898 if ((out->tv_usec -= in->tv_usec) < 0) {
899 out->tv_sec--;
900 out->tv_usec += 1000000;
901 }
902 out->tv_sec -= in->tv_sec;
903 }
904
905
906 /*
907 * Construct an Internet address representation.
908 * If the nflag has been supplied, give
909 * numeric value, otherwise try for symbolic name.
910 */
911 char *
912 inetname(in)
913 struct in_addr in;
914 {
915 register char *cp;
916 static char line[50];
917 struct hostent *hp;
918 static char domain[MAXHOSTNAMELEN + 1];
919 static int first = 1;
920
921 if (first && !nflag) {
922 first = 0;
923 if (gethostname(domain, MAXHOSTNAMELEN) == 0 &&
924 (cp = strrchr(domain, '.')))
925 (void) strcpy(domain, cp + 1);
926 else
927 domain[0] = 0;
928 }
929 cp = 0;
930 if (!nflag && in.s_addr != INADDR_ANY) {
931 hp = gethostbyaddr((char *)&in, sizeof (in), AF_INET);
932 if (hp) {
933 if ((cp = strrchr(hp->h_name, '.')) &&
934 !strcmp(cp + 1, domain))
935 *cp = 0;
936 cp = hp->h_name;
937 }
938 }
939 if (cp)
940 (void) strcpy(line, cp);
941 else {
942 in.s_addr = ntohl(in.s_addr);
943 #define C(x) ((x) & 0xff)
944 Sprintf(line, "%lu.%lu.%lu.%lu", C(in.s_addr >> 24),
945 C(in.s_addr >> 16), C(in.s_addr >> 8), C(in.s_addr));
946 }
947 return (line);
948 }
949
950 void
951 usage()
952 {
953 (void)fprintf(stderr,
954 "usage: traceroute [-dnrv] [-m max_ttl] [-p port#] [-q nqueries]\n\t\
955 [-s src_addr] [-t tos] [-w wait] host [data size]\n");
956 exit(1);
957 }