home *** CD-ROM | disk | FTP | other *** search
/ PC Online 1996 December / PCO1296.ISO / filesbbs / os2 / tracerte.arj / TRACEROU.C < prev    next >
Encoding:
C/C++ Source or Header  |  1995-04-13  |  26.1 KB  |  886 lines

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