Traceroute源码

Traceroute允许确定IP数据报从本地主机游历到某个远程主机所经过的路径。traceroute使用IPv4的TTL字段或IPv6的跳限字段以及两种ICMP消息。它一开始向目的地发送一个TTL(或跳限)为1的数据报。这个数据报导致第一跳路由器返送一个ICMP“time exceeded in transmit”(传输中超时)错误。接着它递增TTL一次发送一个UDP数据报,从而逐步确定下一跳路由器。当某个UDP数据报到达最终目的地时,目标是由这个主机返送一个ICMP“port unreachable(端口不可达)“错误。这个目标通过向一个随机选取的(但愿)未被目的主机使用的端口发送UDP数据报得以实现。

traceroute
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/udp.h>

#define BUFSIZE  1500

struct rec{
    u_short rec_seq;
    u_short rec_ttl;
    struct timeval  rec_tv;
};

char recvbuf[BUFSIZE];
char sendbuf[BUFSIZE];

int     datalen;
char *host;
u_short sport, dport;
int     nsent;
pid_t  pid;
int     probe, nprobes;
int     sendfd, recvfd;
int     ttl, max_ttl;
int     verbose;
int     gotalarm;

const char *icmpcode_v4(int);
const char *icmpcode_v6(int);
int recv_v4(int ,struct timeval *);
int recv_v6(int ,struct timeval *);
void sig_alrm(int );
void traceloop(void);
void tv_sub(struct timeval *, struct timeval *);

struct proto {
    const char *(*icmpcode)(int);
    int             (*recv)(int , struct timeval *);
    struct        sockaddr *sasend;
    struct        sockaddr *sarecv;
    struct        sockaddr *salast;
    struct        sockaddr *sabind;
    socklen_t    salen;
    int             icmpproto;
    int             ttllevel;
    int             ttloptname;
}*pr;

#ifdef  IPV6
#include <netinet/ip6.h>
#include <netinet/icmp6.h>
#endif

struct proto proto_v4 = { icmpcode_v4, recv_v4, NULL, NULL, NULL, NULL, 0,
        IPPROTO_ICMP, IPPROTO_IP, IP_TTL};
#ifdef IPV6
struct proto proto_v6 ={icmpcode_v6, recv_v6, NULL, NULL, NULL, 0,
        IPPROTO_ICMPV6, IPPROTO_IPV6, IPV6_UNICAST_HOPS};
#endif

int datalen = sizeof(struct rec);
int max_ttl = 30;
int nprobes = 3;
u_short dport = 32768 + 666;

int main(int argc, char **argv)
{
    int c;
    struct addrinfo *a;
    char *h;

    opterr = 0;
    while( ( c = getopt(argc, argv, "m:v")) != -1)
        {
            switch(c)
                {
                    case 'm':
                        if( ( max_ttl = atoi(optarg)) <= 1)
                            printf("invalid -m value");
                        break;
                    case 'v':
                        verbose++;
                        break;
                    case '?':
                        printf("unrecognized option:%c", c);
                }
        }

    if( optind != argc -1)
        printf("usage : traceroute [ -m <maxttl> -v] <hostname>");
    host = argv[optind];

    pid = getpid();
    signal(SIGALRM, sig_alrm);

    ai = host_serv(host, NULL, 0, 0);

      h = sock_ntop_host(ai->ai_addr, ai->ai_addrlen);
    printf("traceroute to %s (%s): %d hops max, %d data bytes \n", ai->ai_canonname? ai->ai_canonname:h, h,max_ttl, datalen);

    if ( ai->ai_family == AF_INET  )
        {
            pr = &proto_v4;
#ifdef  IPV6
         }
    else if (ai->ai_family == AF_INET6)
        {
            pr = &proto_v6;
            if(IN6_IS_ADDR_V4MAPPED(&(((struct sockaddr_in6 *) ai->ai_addr)->sin6_addr)))
                printf("cannot traceroute IPV4-mapped IPV6 address");
#endif  
        }
    else
        printf("unknown address family  %d", ai->ai_family);
    pr->sasend = ai->si_addr;
    pr->sarecv = calloc(1, ai->ai_addrlen);
    pr->salast = calloc(1, ai->ai_addrlen);
    pr->sabind = calloc(1, ai->ai_addrlen);
    pr->salen =ai->ai_addrlen;

    traceloop();

    exit();

}

void traceloop(void)
{
    int seq, code, done;
    double rtt;
    struct rec *rec;
    struct timeval tvrecv;

    recvfd = socket(pr->sasend->sa_family, SOCK_RAW, pr->icmpproto);    /*创建两个套接字*/
    setuid(getuid());

#ifdef IPV6
    if ( pr->sasend->sa_family == AF_INET6 && verbose == 0)                  /*设置ICMPv6接收过滤器*/
        {
            struct icmp6_filter myfilt;
            ICMP6_FILTER_SETBLOCKALL(&myfilt);
            ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &myfilt);
            ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &myfilt);
            setsockopt(recvfd, IPPROTO_IPV6, ICMP6_FILTER,
                    &myfilt, sizeof(myfilt));
        }
#endif

    sendfd = socket(pr->sasend->sa_family,SOCK_DGRAM, 0);               /*给UDP套接字捆绑源端口*/

    pr->sabind->sa_family = pr->sasend->sa_family;
    sport = (getpid() &0xffff) | 0x8000;
    sock_set_port(pr->sabind, pr->salen, htons(sport));
    bind(sendfd, pr->sabind,  pr->salen);

    sig_alrm(SIGALRM);        /*建立SIGALRM的信号处理函数*/

    seq = 0;
    done = 0;
    for (ttl = 1; ttl < max_ttl && done ==0; ttl ++)        /*主循环,设置TTL或跳限并发送3个探测分组*/
        {
            setsockopt(sendfd, pr->ttllevel, pr->ttloptname, &ttl, sizeof(int));
            bzero( pr->salast , pr->salen);

            printf("%2d", ttl );
            fflush(stdout);

            for( probe = 0; probe < nprobes; probe ++)
                {
                    rec = (struct rec*) sendbuf;
                    rec->rec_seq = ++seq;
                    rec->rec_ttl = ttl;
                    gettimeofday(&rec->rec_tv, NULL);

                    sock_set_port(pr->sasend, pr->salen, htons(dport+ seq));     /*设置目的端口并发送UDP数据报*/
                    sendto(sendfd, sendbuf,datalen, 0, pr->sasend, pr->salen);

                    if( ( code = (*pr->recv)(seq, &tvrecv)) == -3)    /*读取ICMP消息*/
                        printf(" * ");
                    else                     /*显示应答*/
                        {
                            char str[NI_MAXHOST];

                            if( sock_cmp_addr( pr->sarecv, pr->salast, pr->salen ) != 0)
                                {
                                    if( getnameinfo(pr->sarecv, pr->salen, str, sizeof(str),NULL, 0, 0) == 0)
                                        {
                                            printf(" %s (%s)", str, sock_ntop_host(pr->sarecv, pr->salen));
                                        }
                                    else
                                        printf("%s", sock_ntop_host(pr->sarecv, pr->salen));
                                    memcpy( pr->salast, pr->sarecv, pr->salen);
                                }
                            tv_sub(&tvrecv, &rec->rec_tv);
                            rtt = tvrecv.tv_sec*1000.0 + tvrecv.tv_usec/1000.0;
                            printf(" %.3f ms", rtt);

                            if( code == -1)
                                done++;
                            else if(code >= 0)
                                printf(" (ICMP %s)", (*pr->icmpcode)(code));
                        }
                    fflush(stdout);
                }
            printf("\n");
        }
}

int recv_v4(int seq, struct timeval *tv)
{
    int hlen1, hlen2, icmplen ,ret;
    socklen_t len;
    ssize_t n;
    struct ip *ip, *hip;
    struct icmp *icmp;
    struct udphdr *udp;

    gotalarm = 0;
    alarm(3);           /*设置报警时钟并读入每个ICMP消息*/
    for( ; ;)
        {
            if(gotalarm)
                return (-3);
            len = pr->salen;
            n = recvfrom(recvfd, recvbuf, sizeof(recvbuf), 0, pr->sarecv, &len);
            if( n < 0)
                {
                    if ( errno == EINTR)
                        continue;
                    else
                        printf("recvfrom error");
                }
            ip = (struct ip *) recvbuf;                /*获取ICMP首部指针*/
            hlen1 = ip->ip_hl << 2;

            icmp = (struct icmp *) (recvbuf + hlen1);
            if( (icmplen = n - hlen1 ) < 8)
                continue;

            if( icmp->icmp_type == ICMP_TIMXCEED &&
                                icmp->icmp_code == ICMP_TIMXCEED_INTRANS)   /*处理ICMP传输中超时错误*/
                {
                    if( icmplen < 8 + sizeof(struct ip))
                        continue;

                    hip = (struct ip *)( recvbuf + hlen1 + 8);
                    hlen2 = hip->ip_hl << 2;
                    if( icmplen < 8 + hlen2 + 4)
                        continue;

                    udp = (struct udphdr *) (recvbuf + hlen1 + 8 + hlen2);
                    if( hip->ip_p == IPPROTO_UDP && udp->uh_sport == htons(sport)
                                && udp->uh_dport == htons(dport + seq))
                        {
                            ret = -2;
                            break;
                        }
                    }
            else if ( icmp->icmp_type == ICMP_UNREACH)/*处理ICMP传输中不可达错误*/
                {
                    if ( icmplen < 8 + sizeof( struct ip) )
                        continue;

                    hip = (struct ip *)(recvbuf + hlen1 + 8);
                    hlen2 = hip->ip_hl << 2;
                    if( icmplen < 8 + hlen2 + 4)
                        continue;

                    udp = (struct udphdr *) (recvbuf + hlen1 + 8 + hlen2);
                    if( hip->ip_p == IPPROTO_UDP && udp->uh_sport == htons(sport)
                                        && udp->uh_dport == htons(dport + seq))
                        {
                            if( icmp->icmp_code == ICMP_UNREACH_PORT)
                                ret = -1;
                            else
                                ret = icmp->icmp_code;
                            break;
                        }
                }
            if( verbose)
                {
                    printf(" (from %s: type = %d, code = %d)\n",sock_ntop_host(pr->sarecv, pr->salen),
                        icmp->icmp_type, icmp->icmp_code);

                }
          }
    alarm(0);
    gettimeofday(tv, NULL);
    return (ret);
}

void sig_alrm(int signo)
{
    gotalarm = 1;
    return;
}

int recv_v6(int seq, struct timeval *tv)
{
#ifdef IPV6
    int  hlen2, icmp6len ,ret;
    socklen_t len;
    ssize_t n;
    struct ip6_hdr  *hip6;
    struct icmp6_hdr  *icmp6;
    struct udphdr *udp;

    gotalarm = 0;
    alarm(3);
    for( ; ;)
        {
            if(gotalarm)
                return (-3);
            len = pr->salen;
            n = recvfrom(recvfd, recvbuf, sizeof(recvbuf), 0, pr->sarecv, &len);
            if( n < 0)
                {
                    if ( errno == EINTR)
                        continue;
                    else
                        printf("recvfrom error");
                }

            icmp6 = (struct icmp6_hdr *) recvbuf ;
            if( (icmp6len = n ) < 8)
                continue;

            if( icmp6->icmp6_type == ICMP6_TIME_EXCEEDED &&
                    icmp6->icmp6_code == CMP6_TIME_EXCEEDED_INTRANS)
                {
                    if( icmp6len < 8 + sizeof(struct ip6_hdr) + 4)
                        continue;

                    hip6 = (struct ip6_hdr *)( recvbuf+ 8);
                    hlen2 = sizeof( struct ip6_hdr);

                    udp = (struct udphdr *) (recvbuf  + 8 + hlen2);
                    if( hip6->ip6_nxt == IPPROTO_UDP && udp->uh_sport == htons(sport)
                                && udp->uh_dport == htons(dport + seq))
                        {
                            ret = -2;
                            break;
                        }
                    }
            else if ( icmp6->icmp6_type == ICMP6_DST_UNREACH)
                {
                    if ( icmp6len < 8 + sizeof( struct ip6_hdr) + 4) )
                        continue;

                   hip6 = (struct ip6_hdr *)( recvbuf+ 8);
                    hlen2 = sizeof( struct ip6_hdr);

                    udp = (struct udphdr *) (recvbuf  + 8 + hlen2);
                    if( hip6->ip6_nxt == IPPROTO_UDP && udp->uh_sport == htons(sport)
                                && udp->uh_dport == htons(dport + seq))
                        {
                            if( icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)
                                ret = -1;
                            else
                                ret = icmp6->icmp6_code;
                            break;
                        }
                    }
            if( verbose)
                {
                    printf(" (from %s: type = %d, code = %d)\n",sock_ntop_host(pr->sarecv, pr->salen),
                        icmp6->icmp6_type, icmp6->icmp6_code);

                }
          }
    alarm(0);
    gettimeofday(tv, NULL);
    return (ret);
#endif
}

原始套接字提供3个能力:1.进程可以读写ICMPv4、IGMPv4和ICMPv6等分组; 2.进程可以读写内核不处理其协议字段的IP数据报; 3.进程可以自行构造IPv4首部,通常用于诊断目的(亦或不幸地被黑客们所利用).

Comments