dissector: eth: Free allocated record if line is skipped
[netsniff-ng.git] / astraceroute.c
blob1bcb9a4440274126d3d835d67de132682e41b1dd
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 - 2013 Daniel Borkmann.
4 * Subject to the GPL, version 2.
5 */
7 #define _BSD_SOURCE
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <signal.h>
11 #include <getopt.h>
12 #include <ctype.h>
13 #include <stdint.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <sys/socket.h>
17 #include <sys/fsuid.h>
18 #include <fcntl.h>
19 #include <time.h>
20 #include <string.h>
21 #include <asm/byteorder.h>
22 #include <linux/tcp.h>
23 #include <netinet/ip.h>
24 #include <netinet/ip6.h>
25 #include <netinet/in.h>
26 #include <errno.h>
27 #include <netdb.h>
28 #include <sys/time.h>
29 #include <arpa/inet.h>
30 #include <linux/if_ether.h>
31 #include <linux/icmp.h>
32 #include <linux/icmpv6.h>
34 #include "bpf.h"
35 #include "die.h"
36 #include "dev.h"
37 #include "sig.h"
38 #include "tprintf.h"
39 #include "pkt_buff.h"
40 #include "proto.h"
41 #include "xmalloc.h"
42 #include "ioops.h"
43 #include "csum.h"
44 #include "sock.h"
45 #include "geoip.h"
46 #include "ring_rx.h"
47 #include "built_in.h"
49 struct ctx {
50 char *host, *port, *dev, *payload;
51 int init_ttl, max_ttl, dns_resolv, queries, timeout, totlen, rcvlen;
52 int syn, ack, ecn, fin, psh, rst, urg, tos, nofrag, proto, show;
53 int sd_len, dport, latitude;
56 struct proto_ops {
57 int (*assembler)(uint8_t *packet, size_t len, int ttl, int proto,
58 const struct ctx *ctx, const struct sockaddr *dst,
59 const struct sockaddr *src);
60 const struct sock_filter *filter;
61 unsigned int flen;
62 unsigned int min_len_tcp, min_len_icmp;
63 int (*check)(uint8_t *packet, size_t len, int ttl, int id,
64 const struct sockaddr *src);
65 void (*handler)(uint8_t *packet, size_t len, int dns_resolv,
66 int latitude);
69 static sig_atomic_t sigint = 0;
71 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
72 const struct ctx *ctx, const struct sockaddr *dst,
73 const struct sockaddr *src);
74 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
75 const struct ctx *ctx, const struct sockaddr *dst,
76 const struct sockaddr *src);
77 static int check_ipv4(uint8_t *packet, size_t len, int ttl, int id,
78 const struct sockaddr *ss);
79 static void handle_ipv4(uint8_t *packet, size_t len, int dns_resolv,
80 int latitude);
81 static int check_ipv6(uint8_t *packet, size_t len, int ttl, int id,
82 const struct sockaddr *ss);
83 static void handle_ipv6(uint8_t *packet, size_t len, int dns_resolv,
84 int latitude);
86 static const char *short_options = "H:p:nNf:m:i:d:q:x:SAEFPURt:Gl:hv46X:ZuL";
87 static const struct option long_options[] = {
88 {"host", required_argument, NULL, 'H'},
89 {"port", required_argument, NULL, 'p'},
90 {"init-ttl", required_argument, NULL, 'f'},
91 {"max-ttl", required_argument, NULL, 'm'},
92 {"dev", required_argument, NULL, 'd'},
93 {"num-probes", required_argument, NULL, 'q'},
94 {"timeout", required_argument, NULL, 'x'},
95 {"tos", required_argument, NULL, 't'},
96 {"payload", required_argument, NULL, 'X'},
97 {"totlen", required_argument, NULL, 'l'},
98 {"numeric", no_argument, NULL, 'n'},
99 {"latitude", no_argument, NULL, 'L'},
100 {"update", no_argument, NULL, 'u'},
101 {"dns", no_argument, NULL, 'N'},
102 {"ipv4", no_argument, NULL, '4'},
103 {"ipv6", no_argument, NULL, '6'},
104 {"syn", no_argument, NULL, 'S'},
105 {"ack", no_argument, NULL, 'A'},
106 {"urg", no_argument, NULL, 'U'},
107 {"fin", no_argument, NULL, 'F'},
108 {"psh", no_argument, NULL, 'P'},
109 {"rst", no_argument, NULL, 'R'},
110 {"ecn-syn", no_argument, NULL, 'E'},
111 {"show-packet", no_argument, NULL, 'Z'},
112 {"nofrag", no_argument, NULL, 'G'},
113 {"version", no_argument, NULL, 'v'},
114 {"help", no_argument, NULL, 'h'},
115 {NULL, 0, NULL, 0}
118 static const struct sock_filter ipv4_icmp_type_11[] = {
119 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
120 { 0x15, 0, 8, 0x00000800 }, /* jneq #0x800, drop */
121 { 0x30, 0, 0, 0x00000017 }, /* ldb [23] */
122 { 0x15, 0, 6, 0x00000001 }, /* jneq #0x1, drop */
123 { 0x28, 0, 0, 0x00000014 }, /* ldh [20] */
124 { 0x45, 4, 0, 0x00001fff }, /* jset #0x1fff, drop */
125 { 0xb1, 0, 0, 0x0000000e }, /* ldxb 4*([14]&0xf) */
126 { 0x50, 0, 0, 0x0000000e }, /* ldb [x + 14] */
127 { 0x15, 0, 1, 0x0000000b }, /* jneq #0xb, drop */
128 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
129 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
132 static const struct sock_filter ipv6_icmp6_type_3[] = {
133 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
134 { 0x15, 0, 5, 0x000086dd }, /* jneq #0x86dd, drop */
135 { 0x30, 0, 0, 0x00000014 }, /* ldb [20] */
136 { 0x15, 0, 3, 0x0000003a }, /* jneq #0x3a, drop */
137 { 0x30, 0, 0, 0x00000036 }, /* ldb [54] */
138 { 0x15, 0, 1, 0x00000003 }, /* jneq #0x3, drop */
139 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
140 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
143 static const struct proto_ops af_ops[] = {
144 [IPPROTO_IP] = {
145 .assembler = assemble_ipv4,
146 .handler = handle_ipv4,
147 .check = check_ipv4,
148 .filter = ipv4_icmp_type_11,
149 .flen = array_size(ipv4_icmp_type_11),
150 .min_len_tcp = sizeof(struct iphdr) + sizeof(struct tcphdr),
151 .min_len_icmp = sizeof(struct iphdr) + sizeof(struct icmphdr),
153 [IPPROTO_IPV6] = {
154 .assembler = assemble_ipv6,
155 .handler = handle_ipv6,
156 .check = check_ipv6,
157 .filter = ipv6_icmp6_type_3,
158 .flen = array_size(ipv6_icmp6_type_3),
159 .min_len_tcp = sizeof(struct ip6_hdr) + sizeof(struct tcphdr),
160 .min_len_icmp = sizeof(struct ip6_hdr) + sizeof(struct icmp6hdr),
164 static void signal_handler(int number)
166 switch (number) {
167 case SIGINT:
168 sigint = 1;
169 default:
170 break;
174 static void __noreturn help(void)
176 printf("\nastraceroute %s, autonomous system trace route utility\n", VERSION_STRING);
177 puts("http://www.netsniff-ng.org\n\n"
178 "Usage: astraceroute [options]\n"
179 "Options:\n"
180 " -H|--host <host> Host/IPv4/IPv6 to lookup AS route to\n"
181 " -p|--port <port> Hosts port to lookup AS route to\n"
182 " -i|-d|--dev <device> Networking device, e.g. eth0\n"
183 " -f|--init-ttl <ttl> Set initial TTL\n"
184 " -m|--max-ttl <ttl> Set maximum TTL (def: 30)\n"
185 " -q|--num-probes <num> Number of max probes for each hop (def: 2)\n"
186 " -x|--timeout <sec> Probe response timeout in sec (def: 3)\n"
187 " -X|--payload <string> Specify a payload string to test DPIs\n"
188 " -l|--totlen <len> Specify total packet len\n"
189 " -4|--ipv4 Use IPv4-only requests\n"
190 " -6|--ipv6 Use IPv6-only requests\n"
191 " -n|--numeric Do not do reverse DNS lookup for hops\n"
192 " -u|--update Update GeoIP databases\n"
193 " -L|--latitude Show latitude and longtitude\n"
194 " -N|--dns Do a reverse DNS lookup for hops\n"
195 " -S|--syn Set TCP SYN flag\n"
196 " -A|--ack Set TCP ACK flag\n"
197 " -F|--fin Set TCP FIN flag\n"
198 " -P|--psh Set TCP PSH flag\n"
199 " -U|--urg Set TCP URG flag\n"
200 " -R|--rst Set TCP RST flag\n"
201 " -E|--ecn-syn Send ECN SYN packets (RFC3168)\n"
202 " -t|--tos <tos> Set the IP TOS field\n"
203 " -G|--nofrag Set do not fragment bit\n"
204 " -Z|--show-packet Show returned packet on each hop\n"
205 " -v|--version Print version and exit\n"
206 " -h|--help Print this help and exit\n\n"
207 "Examples:\n"
208 " IPv4 trace of AS with TCP SYN probe (this will most-likely pass):\n"
209 " astraceroute -i eth0 -N -S -H netsniff-ng.org\n"
210 " IPv4 trace of AS with TCP ECN SYN probe:\n"
211 " astraceroute -i eth0 -N -E -H netsniff-ng.org\n"
212 " IPv4 trace of AS with TCP FIN probe:\n"
213 " astraceroute -i eth0 -N -F -H netsniff-ng.org\n"
214 " IPv4 trace of AS with Xmas probe:\n"
215 " astraceroute -i eth0 -N -FPU -H netsniff-ng.org\n"
216 " IPv4 trace of AS with Null probe with ASCII payload:\n"
217 " astraceroute -i eth0 -N -H netsniff-ng.org -X \"censor-me\" -Z\n"
218 " IPv6 trace of AS up to www.6bone.net:\n"
219 " astraceroute -6 -i eth0 -S -E -N -H www.6bone.net\n\n"
220 "Note:\n"
221 " If the TCP probe did not give any results, then astraceroute will\n"
222 " automatically probe for classic ICMP packets! To gather more\n"
223 " information about astraceroute's fetched AS numbers, see e.g.\n"
224 " http://bgp.he.net/AS<number>!\n\n"
225 "Please report bugs to <bugs@netsniff-ng.org>\n"
226 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
227 "Swiss federal institute of technology (ETH Zurich)\n"
228 "License: GNU GPL version 2.0\n"
229 "This is free software: you are free to change and redistribute it.\n"
230 "There is NO WARRANTY, to the extent permitted by law.\n");
231 die();
234 static void __noreturn version(void)
236 printf("\nastraceroute %s, autonomous system trace route utility\n", VERSION_LONG);
237 puts("http://www.netsniff-ng.org\n\n"
238 "Please report bugs to <bugs@netsniff-ng.org>\n"
239 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
240 "Swiss federal institute of technology (ETH Zurich)\n"
241 "License: GNU GPL version 2.0\n"
242 "This is free software: you are free to change and redistribute it.\n"
243 "There is NO WARRANTY, to the extent permitted by law.\n");
244 die();
247 static void __assemble_data(uint8_t *packet, size_t len, const char *payload)
249 int i;
251 if (payload == NULL) {
252 for (i = 0; i < len; ++i)
253 packet[i] = (uint8_t) rand();
254 } else {
255 int lmin = min(len, strlen(payload));
257 for (i = 0; i < lmin; ++i)
258 packet[i] = (uint8_t) payload[i];
259 for (i = lmin; i < len; ++i)
260 packet[i] = (uint8_t) rand();
264 static void __assemble_icmp4(uint8_t *packet, size_t len)
266 struct icmphdr *icmph = (struct icmphdr *) packet;
268 bug_on(len < sizeof(struct icmphdr));
270 icmph->type = ICMP_ECHO;
271 icmph->code = 0;
272 icmph->checksum = 0;
275 static void __assemble_icmp6(uint8_t *packet, size_t len)
277 struct icmp6hdr *icmp6h = (struct icmp6hdr *) packet;
279 bug_on(len < sizeof(struct icmp6hdr));
281 icmp6h->icmp6_type = ICMPV6_ECHO_REQUEST;
282 icmp6h->icmp6_code = 0;
283 icmp6h->icmp6_cksum = 0;
286 static void __assemble_tcp(uint8_t *packet, size_t len, int syn, int ack,
287 int urg, int fin, int rst, int psh, int ecn,
288 int dport)
290 struct tcphdr *tcph = (struct tcphdr *) packet;
292 bug_on(len < sizeof(struct tcphdr));
294 tcph->source = htons((uint16_t) rand());
295 tcph->dest = htons((uint16_t) dport);
297 tcph->seq = htonl(rand());
298 tcph->ack_seq = (!!ack ? htonl(rand()) : 0);
300 tcph->doff = 5;
302 tcph->syn = !!syn;
303 tcph->ack = !!ack;
304 tcph->urg = !!urg;
305 tcph->fin = !!fin;
306 tcph->rst = !!rst;
307 tcph->psh = !!psh;
308 tcph->ece = !!ecn;
309 tcph->cwr = !!ecn;
311 tcph->window = htons((uint16_t) (100 + (rand() % 65435)));
312 tcph->urg_ptr = (!!urg ? htons((uint16_t) rand()) : 0);
313 tcph->check = 0;
316 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
317 const struct ctx *ctx, const struct sockaddr *dst,
318 const struct sockaddr *src)
320 uint8_t *data;
321 size_t data_len, off_next = 0;
322 struct iphdr *iph = (struct iphdr *) packet;
324 bug_on(!src || !dst);
325 bug_on(src->sa_family != PF_INET || dst->sa_family != PF_INET);
326 bug_on(len < sizeof(*iph) + min(sizeof(struct tcphdr),
327 sizeof(struct icmphdr)));
329 iph->ihl = 5;
330 iph->version = 4;
331 iph->tos = (uint8_t) ctx->tos;
333 iph->tot_len = htons((uint16_t) len);
334 iph->id = htons((uint16_t) rand());
336 iph->frag_off = ctx->nofrag ? IP_DF : 0;
337 iph->ttl = (uint8_t) ttl;
339 iph->saddr = ((const struct sockaddr_in *) src)->sin_addr.s_addr;
340 iph->daddr = ((const struct sockaddr_in *) dst)->sin_addr.s_addr;
342 iph->protocol = (uint8_t) proto;
344 data = packet + sizeof(*iph);
345 data_len = len - sizeof(*iph);
347 switch (proto) {
348 case IPPROTO_TCP:
349 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
350 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
351 off_next = sizeof(struct tcphdr);
352 break;
353 case IPPROTO_ICMP:
354 __assemble_icmp4(data, data_len);
355 off_next = sizeof(struct icmphdr);
356 break;
357 default:
358 bug();
361 data = packet + sizeof(*iph) + off_next;
362 data_len = len - sizeof(*iph) - off_next;
364 __assemble_data(data, data_len, ctx->payload);
366 iph->check = csum((unsigned short *) packet, ntohs(iph->tot_len) >> 1);
368 return ntohs(iph->id);
371 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
372 const struct ctx *ctx, const struct sockaddr *dst,
373 const struct sockaddr *src)
375 uint8_t *data;
376 size_t data_len, off_next = 0;
377 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
379 bug_on(!src || !dst);
380 bug_on(src->sa_family != PF_INET6 || dst->sa_family != PF_INET6);
381 bug_on(len < sizeof(*ip6h) + min(sizeof(struct tcphdr),
382 sizeof(struct icmp6hdr)));
384 ip6h->ip6_flow = htonl(rand() & 0x000fffff);
385 ip6h->ip6_vfc = 0x60;
387 ip6h->ip6_plen = htons((uint16_t) len - sizeof(*ip6h));
388 ip6h->ip6_nxt = (uint8_t) proto;
389 ip6h->ip6_hlim = (uint8_t) ttl;
391 memcpy(&ip6h->ip6_src, &(((const struct sockaddr_in6 *)
392 src)->sin6_addr), sizeof(ip6h->ip6_src));
393 memcpy(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
394 dst)->sin6_addr), sizeof(ip6h->ip6_dst));
396 data = packet + sizeof(*ip6h);
397 data_len = len - sizeof(*ip6h);
399 switch (proto) {
400 case IPPROTO_TCP:
401 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
402 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
403 off_next = sizeof(struct tcphdr);
404 break;
405 case IPPROTO_ICMP:
406 case IPPROTO_ICMPV6:
407 __assemble_icmp6(data, data_len);
408 off_next = sizeof(struct icmp6hdr);
409 break;
410 default:
411 bug();
414 data = packet + sizeof(*ip6h) + off_next;
415 data_len = len - sizeof(*ip6h) - off_next;
417 __assemble_data(data, data_len, ctx->payload);
419 return ntohl(ip6h->ip6_flow) & 0x000fffff;
422 static int check_ipv4(uint8_t *packet, size_t len, int ttl, int id,
423 const struct sockaddr *ss)
425 struct iphdr *iph = (struct iphdr *) packet;
426 struct iphdr *iph_inner;
427 struct icmphdr *icmph;
429 if (iph->protocol != IPPROTO_ICMP)
430 return -EINVAL;
431 if (iph->daddr != ((const struct sockaddr_in *) ss)->sin_addr.s_addr)
432 return -EINVAL;
434 icmph = (struct icmphdr *) (packet + sizeof(struct iphdr));
435 if (icmph->type != ICMP_TIME_EXCEEDED)
436 return -EINVAL;
437 if (icmph->code != ICMP_EXC_TTL)
438 return -EINVAL;
440 iph_inner = (struct iphdr *) (packet + sizeof(struct iphdr) +
441 sizeof(struct icmphdr));
442 if (ntohs(iph_inner->id) != id)
443 return -EINVAL;
445 return len;
448 static void handle_ipv4(uint8_t *packet, size_t len, int dns_resolv, int latitude)
450 char hbuff[NI_MAXHOST];
451 struct iphdr *iph = (struct iphdr *) packet;
452 struct sockaddr_in sd;
453 struct hostent *hent;
454 const char *as, *country, *city;
456 memset(hbuff, 0, sizeof(hbuff));
457 memset(&sd, 0, sizeof(sd));
458 sd.sin_family = PF_INET;
459 sd.sin_addr.s_addr = iph->saddr;
461 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
462 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
464 as = geoip4_as_name(sd);
465 country = geoip4_country_name(sd);
466 city = geoip4_city_name(sd);
468 if (dns_resolv) {
469 hent = gethostbyaddr(&sd.sin_addr, sizeof(sd.sin_addr), PF_INET);
470 if (hent)
471 printf(" %s (%s)", hent->h_name, hbuff);
472 else
473 printf(" %s", hbuff);
474 } else {
475 printf(" %s", hbuff);
477 if (as)
478 printf(" in %s", as);
479 if (country) {
480 printf(" in %s", country);
481 if (city)
482 printf(", %s", city);
484 if (latitude)
485 printf(" (%f/%f)", geoip4_latitude(sd), geoip4_longitude(sd));
488 static int check_ipv6(uint8_t *packet, size_t len, int ttl, int id,
489 const struct sockaddr *ss)
491 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
492 struct ip6_hdr *ip6h_inner;
493 struct icmp6hdr *icmp6h;
495 if (ip6h->ip6_nxt != 0x3a)
496 return -EINVAL;
497 if (memcmp(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
498 ss)->sin6_addr), sizeof(ip6h->ip6_dst)))
499 return -EINVAL;
501 icmp6h = (struct icmp6hdr *) (packet + sizeof(*ip6h));
502 if (icmp6h->icmp6_type != ICMPV6_TIME_EXCEED)
503 return -EINVAL;
504 if (icmp6h->icmp6_code != ICMPV6_EXC_HOPLIMIT)
505 return -EINVAL;
507 ip6h_inner = (struct ip6_hdr *) (packet + sizeof(*ip6h) + sizeof(*icmp6h));
508 if ((ntohl(ip6h_inner->ip6_flow) & 0x000fffff) != id)
509 return -EINVAL;
511 return len;
514 static void handle_ipv6(uint8_t *packet, size_t len, int dns_resolv, int latitude)
516 char hbuff[NI_MAXHOST];
517 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
518 struct sockaddr_in6 sd;
519 struct hostent *hent;
520 const char *as, *country, *city;
522 memset(hbuff, 0, sizeof(hbuff));
523 memset(&sd, 0, sizeof(sd));
524 sd.sin6_family = PF_INET6;
525 memcpy(&sd.sin6_addr, &ip6h->ip6_src, sizeof(ip6h->ip6_src));
527 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
528 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
530 as = geoip6_as_name(sd);
531 country = geoip6_country_name(sd);
532 city = geoip6_city_name(sd);
534 if (dns_resolv) {
535 hent = gethostbyaddr(&sd.sin6_addr, sizeof(sd.sin6_addr), PF_INET6);
536 if (hent)
537 printf(" %s (%s)", hent->h_name, hbuff);
538 else
539 printf(" %s", hbuff);
540 } else {
541 printf(" %s", hbuff);
543 if (as)
544 printf(" in %s", as);
545 if (country) {
546 printf(" in %s", country);
547 if (city)
548 printf(", %s", city);
550 if (latitude)
551 printf(" (%f/%f)", geoip6_latitude(sd), geoip6_longitude(sd));
554 static void show_trace_info(struct ctx *ctx, const struct sockaddr_storage *ss,
555 const struct sockaddr_storage *sd)
557 char hbuffs[256], hbuffd[256];
559 memset(hbuffd, 0, sizeof(hbuffd));
560 getnameinfo((struct sockaddr *) sd, sizeof(*sd),
561 hbuffd, sizeof(hbuffd), NULL, 0, NI_NUMERICHOST);
563 memset(hbuffs, 0, sizeof(hbuffs));
564 getnameinfo((struct sockaddr *) ss, sizeof(*ss),
565 hbuffs, sizeof(hbuffs), NULL, 0, NI_NUMERICHOST);
567 printf("AS path IPv%d TCP trace from %s to %s:%s (%s) with len %d "
568 "Bytes, %u max hops\n", ctx->proto == IPPROTO_IP ? 4 : 6,
569 hbuffs, hbuffd, ctx->port, ctx->host, ctx->totlen, ctx->max_ttl);
571 printf("Using flags SYN:%d,ACK:%d,ECN:%d,FIN:%d,PSH:%d,RST:%d,URG:%d\n",
572 ctx->syn, ctx->ack, ctx->ecn, ctx->fin, ctx->psh, ctx->rst, ctx->urg);
574 if (ctx->payload)
575 printf("With payload: \'%s\'\n", ctx->payload);
578 static int get_remote_fd(struct ctx *ctx, struct sockaddr_storage *ss,
579 struct sockaddr_storage *sd)
581 int fd = -1, ret, one = 1;
582 struct addrinfo hints, *ahead, *ai;
584 memset(&hints, 0, sizeof(hints));
585 hints.ai_family = PF_UNSPEC;
586 hints.ai_socktype = SOCK_STREAM;
587 hints.ai_protocol = IPPROTO_TCP;
588 hints.ai_flags = AI_NUMERICSERV;
590 ret = getaddrinfo(ctx->host, ctx->port, &hints, &ahead);
591 if (ret < 0)
592 panic("Cannot get address info!\n");
594 for (ai = ahead; ai != NULL && fd < 0; ai = ai->ai_next) {
595 if (!((ai->ai_family == PF_INET6 && ctx->proto == IPPROTO_IPV6) ||
596 (ai->ai_family == PF_INET && ctx->proto == IPPROTO_IP)))
597 continue;
599 fd = socket(ai->ai_family, SOCK_RAW, IPPROTO_RAW);
600 if (fd < 0)
601 continue;
603 memset(ss, 0, sizeof(*ss));
604 ret = device_address(ctx->dev, ai->ai_family, ss);
605 if (ret < 0)
606 panic("Cannot get own device address!\n");
608 ret = bind(fd, (struct sockaddr *) ss, sizeof(*ss));
609 if (ret < 0)
610 panic("Cannot bind socket!\n");
612 memset(sd, 0, sizeof(*sd));
613 memcpy(sd, ai->ai_addr, ai->ai_addrlen);
615 ctx->sd_len = ai->ai_addrlen;
616 ctx->dport = strtoul(ctx->port, NULL, 10);
618 ret = setsockopt(fd, ctx->proto, IP_HDRINCL, &one, sizeof(one));
619 if (ret < 0)
620 panic("Kernel does not support IP_HDRINCL!\n");
622 if (ai->ai_family == PF_INET6) {
623 struct sockaddr_in6 *sd6 = (struct sockaddr_in6 *) sd;
625 sd6->sin6_port = 0;
628 break;
631 freeaddrinfo(ahead);
633 if (fd < 0)
634 panic("Cannot create socket! Does remote "
635 "support IPv%d?!\n",
636 ctx->proto == IPPROTO_IP ? 4 : 6);
638 return fd;
641 static void inject_filter(struct ctx *ctx, int fd)
643 struct sock_fprog bpf_ops;
645 enable_kernel_bpf_jit_compiler();
647 memset(&bpf_ops, 0, sizeof(bpf_ops));
648 bpf_ops.filter = (struct sock_filter *) af_ops[ctx->proto].filter;
649 bpf_ops.len = af_ops[ctx->proto].flen;
651 bpf_attach_to_sock(fd, &bpf_ops);
654 static int __process_node(struct ctx *ctx, int fd, int fd_cap, int ttl,
655 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
656 const struct sockaddr_storage *ss,
657 const struct sockaddr_storage *sd, struct timeval *diff)
659 int pkt_id, ret, timeout;
660 struct pollfd pfd;
661 struct timeval start, end;
663 prepare_polling(fd_cap, &pfd);
665 memset(pkt_snd, 0, ctx->totlen);
666 pkt_id = af_ops[ctx->proto].assembler(pkt_snd, ctx->totlen, ttl,
667 inner_proto, ctx,
668 (const struct sockaddr *) sd,
669 (const struct sockaddr *) ss);
671 ret = sendto(fd, pkt_snd, ctx->totlen, 0, (struct sockaddr *) sd,
672 ctx->sd_len);
673 if (ret < 0)
674 panic("sendto failed: %s\n", strerror(errno));
676 bug_on(gettimeofday(&start, NULL));
678 timeout = (ctx->timeout > 0 ? ctx->timeout : 2) * 1000;
680 ret = poll(&pfd, 1, timeout);
681 if (ret > 0 && pfd.revents & POLLIN && sigint == 0) {
682 bug_on(gettimeofday(&end, NULL));
683 if (diff)
684 timersub(&end, &start, diff);
686 ret = recvfrom(fd_cap, pkt_rcv, ctx->rcvlen, 0, NULL, NULL);
687 if (ret < sizeof(struct ethhdr) + af_ops[ctx->proto].min_len_icmp)
688 return -EIO;
690 return af_ops[ctx->proto].check(pkt_rcv + sizeof(struct ethhdr),
691 ret - sizeof(struct ethhdr), ttl,
692 pkt_id, (const struct sockaddr *) ss);
693 } else {
694 return -EIO;
697 return 0;
700 static void timerdiv(const unsigned long divisor, const struct timeval *tv,
701 struct timeval *result)
703 uint64_t x = ((uint64_t) tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
705 result->tv_sec = x / 1000 / 1000;
706 result->tv_usec = x % (1000 * 1000);
709 static int timevalcmp(const void *t1, const void *t2)
711 if (timercmp((struct timeval *) t1, (struct timeval *) t2, <))
712 return -1;
713 if (timercmp((struct timeval *) t1, (struct timeval *) t2, >))
714 return 1;
716 return 0;
719 static int __process_time(struct ctx *ctx, int fd, int fd_cap, int ttl,
720 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
721 const struct sockaddr_storage *ss,
722 const struct sockaddr_storage *sd)
724 int good = 0, i, j = 0, ret = -EIO, idx, ret_good = -EIO;
725 struct timeval probes[9], *tmp, sum, res;
726 uint8_t *trash = xmalloc(ctx->rcvlen);
727 char *cwait[] = { "-", "\\", "|", "/" };
728 const char *proto_short[] = {
729 [IPPROTO_TCP] = "t",
730 [IPPROTO_ICMP] = "i",
731 [IPPROTO_ICMPV6] = "i",
734 memset(probes, 0, sizeof(probes));
735 for (i = 0; i < array_size(probes) && sigint == 0; ++i) {
736 ret = __process_node(ctx, fd, fd_cap, ttl, inner_proto,
737 pkt_snd, good == 0 ? pkt_rcv : trash,
738 ss, sd, &probes[i]);
739 if (ret > 0) {
740 if (good == 0)
741 ret_good = ret;
742 good++;
745 if (good == 0 && ctx->queries == i)
746 break;
748 usleep(50000);
750 printf("\r%2d: %s", ttl, cwait[j++]);
751 fflush(stdout);
752 if (j >= array_size(cwait))
753 j = 0;
756 if (good == 0) {
757 xfree(trash);
758 return -EIO;
761 tmp = xmalloc(sizeof(struct timeval) * good);
762 for (i = j = 0; i < array_size(probes); ++i) {
763 if (probes[i].tv_sec == 0 && probes[i].tv_usec == 0)
764 continue;
765 tmp[j].tv_sec = probes[i].tv_sec;
766 tmp[j].tv_usec = probes[i].tv_usec;
767 j++;
770 qsort(tmp, j, sizeof(struct timeval), timevalcmp);
772 printf("\r%2d: %s[", ttl, proto_short[inner_proto]);
773 idx = j / 2;
774 switch (j % 2) {
775 case 0:
776 timeradd(&tmp[idx], &tmp[idx - 1], &sum);
777 timerdiv(2, &sum, &res);
778 if (res.tv_sec > 0)
779 printf("%lu sec ", res.tv_sec);
780 printf("%7lu us", res.tv_usec);
781 break;
782 case 1:
783 if (tmp[idx].tv_sec > 0)
784 printf("%lu sec ", tmp[idx].tv_sec);
785 printf("%7lu us", tmp[idx].tv_usec);
786 break;
788 printf("]");
790 xfree(tmp);
791 xfree(trash);
793 return ret_good;
796 static int __probe_remote(struct ctx *ctx, int fd, int fd_cap, int ttl,
797 uint8_t *pkt_snd, uint8_t *pkt_rcv,
798 const struct sockaddr_storage *ss,
799 const struct sockaddr_storage *sd,
800 int inner_proto)
802 int ret = -EIO, tries = ctx->queries;
804 while (tries-- > 0 && sigint == 0) {
805 ret = __process_time(ctx, fd, fd_cap, ttl, inner_proto,
806 pkt_snd, pkt_rcv, ss, sd);
807 if (ret < 0)
808 continue;
810 af_ops[ctx->proto].handler(pkt_rcv + sizeof(struct ethhdr),
811 ret - sizeof(struct ethhdr),
812 ctx->dns_resolv, ctx->latitude);
813 if (ctx->show) {
814 struct pkt_buff *pkt;
816 printf("\n");
817 pkt = pkt_alloc(pkt_rcv, ret);
818 hex_ascii(pkt);
819 tprintf_flush();
820 pkt_free(pkt);
823 break;
826 return ret;
829 static int __process_ttl(struct ctx *ctx, int fd, int fd_cap, int ttl,
830 uint8_t *pkt_snd, uint8_t *pkt_rcv,
831 const struct sockaddr_storage *ss,
832 const struct sockaddr_storage *sd)
834 int ret = -EIO, i;
835 const int inner_protos[] = {
836 IPPROTO_TCP,
837 IPPROTO_ICMP,
840 printf("%2d: ", ttl);
841 fflush(stdout);
843 for (i = 0; i < array_size(inner_protos) && sigint == 0; ++i) {
844 ret = __probe_remote(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv, ss, sd,
845 inner_protos[i]);
846 if (ret > 0)
847 break;
850 if (ret <= 0)
851 printf("\r%2d: ?[ no answer]", ttl);
852 if (ctx->show == 0)
853 printf("\n");
854 if (ctx->show && ret <= 0)
855 printf("\n\n");
857 fflush(stdout);
858 return 0;
861 static int main_trace(struct ctx *ctx)
863 int fd, fd_cap, ifindex, ttl;
864 struct ring dummy_ring;
865 struct sockaddr_storage ss, sd;
866 uint8_t *pkt_snd, *pkt_rcv;
868 fd = get_remote_fd(ctx, &ss, &sd);
869 fd_cap = pf_socket();
871 inject_filter(ctx, fd_cap);
873 ifindex = device_ifindex(ctx->dev);
874 bind_rx_ring(fd_cap, &dummy_ring, ifindex);
876 if (ctx->totlen < af_ops[ctx->proto].min_len_tcp) {
877 ctx->totlen = af_ops[ctx->proto].min_len_tcp;
878 if (ctx->payload)
879 ctx->totlen += strlen(ctx->payload);
882 ctx->rcvlen = device_mtu(ctx->dev) - sizeof(struct ethhdr);
883 if (ctx->totlen >= ctx->rcvlen)
884 panic("Packet len exceeds device MTU!\n");
886 pkt_snd = xmalloc(ctx->totlen);
887 pkt_rcv = xmalloc(ctx->rcvlen);
889 show_trace_info(ctx, &ss, &sd);
891 for (ttl = ctx->init_ttl; ttl <= ctx->max_ttl && sigint == 0; ++ttl)
892 __process_ttl(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv,
893 &ss, &sd);
895 xfree(pkt_snd);
896 xfree(pkt_rcv);
898 close(fd_cap);
899 close(fd);
901 return 0;
904 int main(int argc, char **argv)
906 int c, opt_index, ret;
907 struct ctx ctx;
909 setfsuid(getuid());
910 setfsgid(getgid());
912 srand(time(NULL));
914 memset(&ctx, 0, sizeof(ctx));
915 ctx.init_ttl = 1;
916 ctx.max_ttl = 30;
917 ctx.queries = 2;
918 ctx.timeout = 2;
919 ctx.proto = IPPROTO_IP;
920 ctx.payload = NULL;
921 ctx.dev = xstrdup("eth0");
922 ctx.port = xstrdup("80");
924 while ((c = getopt_long(argc, argv, short_options, long_options,
925 &opt_index)) != EOF) {
926 switch (c) {
927 case 'h':
928 help();
929 break;
930 case 'v':
931 version();
932 break;
933 case 'u':
934 update_geoip();
935 die();
936 break;
937 case 'H':
938 ctx.host = xstrdup(optarg);
939 break;
940 case 'p':
941 if (ctx.port)
942 xfree(ctx.port);
943 ctx.port = xstrdup(optarg);
944 break;
945 case 'n':
946 ctx.dns_resolv = 0;
947 break;
948 case '4':
949 ctx.proto = IPPROTO_IP;
950 break;
951 case '6':
952 ctx.proto = IPPROTO_IPV6;
953 break;
954 case 'Z':
955 ctx.show = 1;
956 break;
957 case 'N':
958 ctx.dns_resolv = 1;
959 break;
960 case 'f':
961 ctx.init_ttl = atoi(optarg);
962 if (ctx.init_ttl <= 0)
963 help();
964 break;
965 case 'm':
966 ctx.max_ttl = atoi(optarg);
967 if (ctx.max_ttl <= 0)
968 help();
969 break;
970 case 'i':
971 case 'd':
972 free(ctx.dev);
973 ctx.dev = xstrdup(optarg);
974 break;
975 case 'q':
976 ctx.queries = atoi(optarg);
977 if (ctx.queries <= 0)
978 help();
979 break;
980 case 'x':
981 ctx.timeout = atoi(optarg);
982 if (ctx.timeout <= 0)
983 help();
984 break;
985 case 'L':
986 ctx.latitude = 1;
987 break;
988 case 'S':
989 ctx.syn = 1;
990 break;
991 case 'A':
992 ctx.ack = 1;
993 break;
994 case 'F':
995 ctx.fin = 1;
996 break;
997 case 'U':
998 ctx.urg = 1;
999 break;
1000 case 'P':
1001 ctx.psh = 1;
1002 break;
1003 case 'R':
1004 ctx.rst = 1;
1005 break;
1006 case 'E':
1007 ctx.syn = 1;
1008 ctx.ecn = 1;
1009 break;
1010 case 't':
1011 ctx.tos = atoi(optarg);
1012 if (ctx.tos < 0)
1013 help();
1014 break;
1015 case 'G':
1016 ctx.nofrag = 1;
1017 break;
1018 case 'X':
1019 ctx.payload = xstrdup(optarg);
1020 break;
1021 case 'l':
1022 ctx.totlen = atoi(optarg);
1023 if (ctx.totlen <= 0)
1024 help();
1025 break;
1026 case '?':
1027 switch (optopt) {
1028 case 'H':
1029 case 'p':
1030 case 'f':
1031 case 'm':
1032 case 'i':
1033 case 'd':
1034 case 'q':
1035 case 'x':
1036 case 'X':
1037 case 't':
1038 case 'l':
1039 panic("Option -%c requires an argument!\n",
1040 optopt);
1041 default:
1042 if (isprint(optopt))
1043 printf("Unknown option character `0x%X\'!\n", optopt);
1044 die();
1046 default:
1047 break;
1051 if (argc < 3 || !ctx.host || !ctx.port || ctx.init_ttl > ctx.max_ttl ||
1052 ctx.init_ttl > MAXTTL || ctx.max_ttl > MAXTTL)
1053 help();
1055 if (!device_up_and_running(ctx.dev))
1056 panic("Networking device not up and running!\n");
1057 if (device_mtu(ctx.dev) <= ctx.totlen)
1058 panic("Packet larger than device MTU!\n");
1060 register_signal(SIGHUP, signal_handler);
1061 register_signal(SIGINT, signal_handler);
1063 tprintf_init();
1064 init_geoip(1);
1066 ret = main_trace(&ctx);
1068 destroy_geoip();
1069 tprintf_cleanup();
1071 free(ctx.dev);
1072 free(ctx.host);
1073 free(ctx.port);
1074 free(ctx.payload);
1076 return ret;