ring: use xzmalloc_aligned
[netsniff-ng.git] / astraceroute.c
blob21e9a90e8c861e39c3903388e4e8fffa087d0c7b
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 #define _DEFAULT_SOURCE
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <signal.h>
12 #include <getopt.h>
13 #include <ctype.h>
14 #include <stdint.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/socket.h>
18 #include <sys/fsuid.h>
19 #include <fcntl.h>
20 #include <time.h>
21 #include <string.h>
22 #include <asm/byteorder.h>
23 #include <linux/tcp.h>
24 #include <netinet/if_ether.h>
25 #include <netinet/ip.h>
26 #include <netinet/ip6.h>
27 #include <netinet/in.h>
28 #include <errno.h>
29 #include <netdb.h>
30 #include <sys/time.h>
31 #include <arpa/inet.h>
32 #include <linux/icmp.h>
33 #include <linux/icmpv6.h>
35 #include "bpf.h"
36 #include "die.h"
37 #include "dev.h"
38 #include "sig.h"
39 #include "config.h"
40 #include "tprintf.h"
41 #include "pkt_buff.h"
42 #include "proto.h"
43 #include "xmalloc.h"
44 #include "csum.h"
45 #include "sock.h"
46 #include "geoip.h"
47 #include "ring.h"
48 #include "built_in.h"
50 struct ctx {
51 char *host, *port, *dev, *payload, *bind_addr;
52 size_t totlen, rcvlen;
53 socklen_t sd_len;
54 int init_ttl, max_ttl, dns_resolv, queries, timeout;
55 int syn, ack, ecn, fin, psh, rst, urg, tos, nofrag, proto, show;
56 int dport, latitude;
59 struct proto_ops {
60 int (*assembler)(uint8_t *packet, size_t len, int ttl, int proto,
61 const struct ctx *ctx, const struct sockaddr *dst,
62 const struct sockaddr *src);
63 const struct sock_filter *filter;
64 unsigned int flen;
65 size_t min_len_tcp, min_len_icmp;
66 int (*check)(uint8_t *packet, size_t len, int ttl, int id,
67 const struct sockaddr *src);
68 void (*handler)(uint8_t *packet, size_t len, int dns_resolv,
69 int latitude);
72 static sig_atomic_t sigint = 0;
74 static int assemble_ipv4(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 assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
78 const struct ctx *ctx, const struct sockaddr *dst,
79 const struct sockaddr *src);
80 static int check_ipv4(uint8_t *packet, size_t len, int ttl, int id,
81 const struct sockaddr *ss);
82 static void handle_ipv4(uint8_t *packet, size_t len, int dns_resolv,
83 int latitude);
84 static int check_ipv6(uint8_t *packet, size_t len, int ttl, int id,
85 const struct sockaddr *ss);
86 static void handle_ipv6(uint8_t *packet, size_t len, int dns_resolv,
87 int latitude);
89 static const char *short_options = "H:p:nNf:m:b:i:d:q:x:SAEFPURt:Gl:hv46X:ZuL";
90 static const struct option long_options[] = {
91 {"host", required_argument, NULL, 'H'},
92 {"port", required_argument, NULL, 'p'},
93 {"init-ttl", required_argument, NULL, 'f'},
94 {"max-ttl", required_argument, NULL, 'm'},
95 {"bind", required_argument, NULL, 'b'},
96 {"dev", required_argument, NULL, 'd'},
97 {"num-probes", required_argument, NULL, 'q'},
98 {"timeout", required_argument, NULL, 'x'},
99 {"tos", required_argument, NULL, 't'},
100 {"payload", required_argument, NULL, 'X'},
101 {"totlen", required_argument, NULL, 'l'},
102 {"numeric", no_argument, NULL, 'n'},
103 {"latitude", no_argument, NULL, 'L'},
104 {"update", no_argument, NULL, 'u'},
105 {"dns", no_argument, NULL, 'N'},
106 {"ipv4", no_argument, NULL, '4'},
107 {"ipv6", no_argument, NULL, '6'},
108 {"syn", no_argument, NULL, 'S'},
109 {"ack", no_argument, NULL, 'A'},
110 {"urg", no_argument, NULL, 'U'},
111 {"fin", no_argument, NULL, 'F'},
112 {"psh", no_argument, NULL, 'P'},
113 {"rst", no_argument, NULL, 'R'},
114 {"ecn-syn", no_argument, NULL, 'E'},
115 {"show-packet", no_argument, NULL, 'Z'},
116 {"nofrag", no_argument, NULL, 'G'},
117 {"version", no_argument, NULL, 'v'},
118 {"help", no_argument, NULL, 'h'},
119 {NULL, 0, NULL, 0}
122 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
123 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
124 "Swiss federal institute of technology (ETH Zurich)\n"
125 "License: GNU GPL version 2.0\n"
126 "This is free software: you are free to change and redistribute it.\n"
127 "There is NO WARRANTY, to the extent permitted by law.";
129 static const struct sock_filter ipv4_icmp_type_11[] = {
130 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
131 { 0x15, 0, 8, 0x00000800 }, /* jneq #0x800, drop */
132 { 0x30, 0, 0, 0x00000017 }, /* ldb [23] */
133 { 0x15, 0, 6, 0x00000001 }, /* jneq #0x1, drop */
134 { 0x28, 0, 0, 0x00000014 }, /* ldh [20] */
135 { 0x45, 4, 0, 0x00001fff }, /* jset #0x1fff, drop */
136 { 0xb1, 0, 0, 0x0000000e }, /* ldxb 4*([14]&0xf) */
137 { 0x50, 0, 0, 0x0000000e }, /* ldb [x + 14] */
138 { 0x15, 0, 1, 0x0000000b }, /* jneq #0xb, drop */
139 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
140 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
143 static const struct sock_filter ipv6_icmp6_type_3[] = {
144 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
145 { 0x15, 0, 5, 0x000086dd }, /* jneq #0x86dd, drop */
146 { 0x30, 0, 0, 0x00000014 }, /* ldb [20] */
147 { 0x15, 0, 3, 0x0000003a }, /* jneq #0x3a, drop */
148 { 0x30, 0, 0, 0x00000036 }, /* ldb [54] */
149 { 0x15, 0, 1, 0x00000003 }, /* jneq #0x3, drop */
150 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
151 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
154 static const struct proto_ops af_ops[] = {
155 [IPPROTO_IP] = {
156 .assembler = assemble_ipv4,
157 .handler = handle_ipv4,
158 .check = check_ipv4,
159 .filter = ipv4_icmp_type_11,
160 .flen = array_size(ipv4_icmp_type_11),
161 .min_len_tcp = sizeof(struct iphdr) + sizeof(struct tcphdr),
162 .min_len_icmp = sizeof(struct iphdr) + sizeof(struct icmphdr),
164 [IPPROTO_IPV6] = {
165 .assembler = assemble_ipv6,
166 .handler = handle_ipv6,
167 .check = check_ipv6,
168 .filter = ipv6_icmp6_type_3,
169 .flen = array_size(ipv6_icmp6_type_3),
170 .min_len_tcp = sizeof(struct ip6_hdr) + sizeof(struct tcphdr),
171 .min_len_icmp = sizeof(struct ip6_hdr) + sizeof(struct icmp6hdr),
175 static void signal_handler(int number)
177 switch (number) {
178 case SIGINT:
179 case SIGQUIT:
180 case SIGTERM:
181 sigint = 1;
182 default:
183 break;
187 static void __noreturn help(void)
189 printf("astraceroute %s, autonomous system trace route utility\n", VERSION_STRING);
190 puts("http://www.netsniff-ng.org\n\n"
191 "Usage: astraceroute [options]\n"
192 "Options:\n"
193 " -H|--host <host> Host/IPv4/IPv6 to lookup AS route to\n"
194 " -p|--port <port> Hosts port to lookup AS route to\n"
195 " -i|-d|--dev <device> Networking device, e.g. eth0\n"
196 " -b|--bind <IP> IP address to bind to, Must specify -6 for an IPv6 address\n"
197 " -f|--init-ttl <ttl> Set initial TTL\n"
198 " -m|--max-ttl <ttl> Set maximum TTL (def: 30)\n"
199 " -q|--num-probes <num> Number of max probes for each hop (def: 2)\n"
200 " -x|--timeout <sec> Probe response timeout in sec (def: 3)\n"
201 " -X|--payload <string> Specify a payload string to test DPIs\n"
202 " -l|--totlen <len> Specify total packet len\n"
203 " -4|--ipv4 Use IPv4-only requests\n"
204 " -6|--ipv6 Use IPv6-only requests\n"
205 " -n|--numeric Do not do reverse DNS lookup for hops\n"
206 " -u|--update Update GeoIP databases\n"
207 " -L|--latitude Show latitude and longitude\n"
208 " -N|--dns Do a reverse DNS lookup for hops\n"
209 " -S|--syn Set TCP SYN flag\n"
210 " -A|--ack Set TCP ACK flag\n"
211 " -F|--fin Set TCP FIN flag\n"
212 " -P|--psh Set TCP PSH flag\n"
213 " -U|--urg Set TCP URG flag\n"
214 " -R|--rst Set TCP RST flag\n"
215 " -E|--ecn-syn Send ECN SYN packets (RFC3168)\n"
216 " -t|--tos <tos> Set the IP TOS field\n"
217 " -G|--nofrag Set do not fragment bit\n"
218 " -Z|--show-packet Show returned packet on each hop\n"
219 " -v|--version Print version and exit\n"
220 " -h|--help Print this help and exit\n\n"
221 "Examples:\n"
222 " IPv4 trace of AS with TCP SYN probe (this will most-likely pass):\n"
223 " astraceroute -i eth0 -N -S -H netsniff-ng.org\n"
224 " IPv4 trace of AS with TCP ECN SYN probe:\n"
225 " astraceroute -i eth0 -N -E -H netsniff-ng.org\n"
226 " IPv4 trace of AS with TCP FIN probe:\n"
227 " astraceroute -i eth0 -N -F -H netsniff-ng.org\n"
228 " IPv4 trace of AS with Xmas probe:\n"
229 " astraceroute -i eth0 -N -FPU -H netsniff-ng.org\n"
230 " IPv4 trace of AS with Null probe with ASCII payload:\n"
231 " astraceroute -i eth0 -N -H netsniff-ng.org -X \"censor-me\" -Z\n"
232 " IPv6 trace of AS up to www.6bone.net:\n"
233 " astraceroute -6 -i eth0 -S -E -N -H www.6bone.net\n\n"
234 "Note:\n"
235 " If the TCP probe did not give any results, then astraceroute will\n"
236 " automatically probe for classic ICMP packets! To gather more\n"
237 " information about astraceroute's fetched AS numbers, see e.g.\n"
238 " http://bgp.he.net/AS<number>!\n");
239 puts(copyright);
240 die();
243 static void __noreturn version(void)
245 printf("astraceroute %s, Git id: %s\n", VERSION_LONG, GITVERSION);
246 puts("autonomous system trace route utility\n"
247 "http://www.netsniff-ng.org\n");
248 puts(copyright);
249 die();
252 static void __assemble_data(uint8_t *packet, size_t len, const char *payload)
254 size_t i;
256 if (payload == NULL) {
257 for (i = 0; i < len; ++i)
258 packet[i] = (uint8_t) rand();
259 } else {
260 size_t lmin = min(len, strlen(payload));
262 for (i = 0; i < lmin; ++i)
263 packet[i] = (uint8_t) payload[i];
264 for (i = lmin; i < len; ++i)
265 packet[i] = (uint8_t) rand();
269 static void __assemble_icmp4(uint8_t *packet, size_t len)
271 struct icmphdr *icmph = (struct icmphdr *) packet;
273 bug_on(len < sizeof(struct icmphdr));
275 icmph->type = ICMP_ECHO;
276 icmph->code = 0;
277 icmph->checksum = 0;
280 static void __assemble_icmp6(uint8_t *packet, size_t len)
282 struct icmp6hdr *icmp6h = (struct icmp6hdr *) packet;
284 bug_on(len < sizeof(struct icmp6hdr));
286 icmp6h->icmp6_type = ICMPV6_ECHO_REQUEST;
287 icmp6h->icmp6_code = 0;
288 icmp6h->icmp6_cksum = 0;
291 static void __assemble_tcp(uint8_t *packet, size_t len, int syn, int ack,
292 int urg, int fin, int rst, int psh, int ecn,
293 int dport)
295 struct tcphdr *tcph = (struct tcphdr *) packet;
297 bug_on(len < sizeof(struct tcphdr));
299 tcph->source = htons((uint16_t) rand());
300 tcph->dest = htons((uint16_t) dport);
302 tcph->seq = htonl(rand());
303 tcph->ack_seq = (!!ack ? htonl(rand()) : 0);
305 tcph->doff = 5;
307 tcph->syn = !!syn;
308 tcph->ack = !!ack;
309 tcph->urg = !!urg;
310 tcph->fin = !!fin;
311 tcph->rst = !!rst;
312 tcph->psh = !!psh;
313 tcph->ece = !!ecn;
314 tcph->cwr = !!ecn;
316 tcph->window = htons((uint16_t) (100 + (rand() % 65435)));
317 tcph->urg_ptr = (!!urg ? htons((uint16_t) rand()) : 0);
318 tcph->check = 0;
321 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
322 const struct ctx *ctx, const struct sockaddr *dst,
323 const struct sockaddr *src)
325 uint8_t *data;
326 size_t data_len, off_next = 0;
327 struct iphdr *iph = (struct iphdr *) packet;
329 bug_on(!src || !dst);
330 bug_on(src->sa_family != PF_INET || dst->sa_family != PF_INET);
331 bug_on(len < sizeof(*iph) + min(sizeof(struct tcphdr),
332 sizeof(struct icmphdr)));
334 iph->ihl = 5;
335 iph->version = 4;
336 iph->tos = (uint8_t) ctx->tos;
338 iph->tot_len = htons((uint16_t) len);
339 iph->id = htons((uint16_t) rand());
341 iph->frag_off = ctx->nofrag ? IP_DF : 0;
342 iph->ttl = (uint8_t) ttl;
344 iph->saddr = ((const struct sockaddr_in *) src)->sin_addr.s_addr;
345 iph->daddr = ((const struct sockaddr_in *) dst)->sin_addr.s_addr;
347 iph->protocol = (uint8_t) proto;
349 data = packet + sizeof(*iph);
350 data_len = len - sizeof(*iph);
352 switch (proto) {
353 case IPPROTO_TCP:
354 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
355 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
356 off_next = sizeof(struct tcphdr);
357 break;
358 case IPPROTO_ICMP:
359 __assemble_icmp4(data, data_len);
360 off_next = sizeof(struct icmphdr);
361 break;
362 default:
363 bug();
366 data = packet + sizeof(*iph) + off_next;
367 data_len = len - sizeof(*iph) - off_next;
369 __assemble_data(data, data_len, ctx->payload);
371 iph->check = csum((unsigned short *) packet, ntohs(iph->tot_len) >> 1);
373 return ntohs(iph->id);
376 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
377 const struct ctx *ctx, const struct sockaddr *dst,
378 const struct sockaddr *src)
380 uint8_t *data;
381 size_t data_len, off_next = 0;
382 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
384 bug_on(!src || !dst);
385 bug_on(src->sa_family != PF_INET6 || dst->sa_family != PF_INET6);
386 bug_on(len < sizeof(*ip6h) + min(sizeof(struct tcphdr),
387 sizeof(struct icmp6hdr)));
389 ip6h->ip6_flow = htonl(rand() & 0x000fffff);
390 ip6h->ip6_vfc = 0x60;
392 ip6h->ip6_plen = htons((uint16_t) len - sizeof(*ip6h));
393 ip6h->ip6_nxt = (uint8_t) proto;
394 ip6h->ip6_hlim = (uint8_t) ttl;
396 memcpy(&ip6h->ip6_src, &(((const struct sockaddr_in6 *)
397 src)->sin6_addr), sizeof(ip6h->ip6_src));
398 memcpy(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
399 dst)->sin6_addr), sizeof(ip6h->ip6_dst));
401 data = packet + sizeof(*ip6h);
402 data_len = len - sizeof(*ip6h);
404 switch (proto) {
405 case IPPROTO_TCP:
406 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
407 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
408 off_next = sizeof(struct tcphdr);
409 break;
410 case IPPROTO_ICMP:
411 case IPPROTO_ICMPV6:
412 __assemble_icmp6(data, data_len);
413 off_next = sizeof(struct icmp6hdr);
414 break;
415 default:
416 bug();
419 data = packet + sizeof(*ip6h) + off_next;
420 data_len = len - sizeof(*ip6h) - off_next;
422 __assemble_data(data, data_len, ctx->payload);
424 return ntohl(ip6h->ip6_flow) & 0x000fffff;
427 static int check_ipv4(uint8_t *packet, size_t len, int ttl __maybe_unused,
428 int id, const struct sockaddr *ss)
430 struct iphdr *iph = (struct iphdr *) packet;
431 struct iphdr *iph_inner;
432 struct icmphdr *icmph;
434 if (iph->protocol != IPPROTO_ICMP)
435 return -EINVAL;
436 if (iph->daddr != ((const struct sockaddr_in *) ss)->sin_addr.s_addr)
437 return -EINVAL;
439 icmph = (struct icmphdr *) (packet + sizeof(struct iphdr));
440 if (icmph->type != ICMP_TIME_EXCEEDED)
441 return -EINVAL;
442 if (icmph->code != ICMP_EXC_TTL)
443 return -EINVAL;
445 iph_inner = (struct iphdr *) (packet + sizeof(struct iphdr) +
446 sizeof(struct icmphdr));
447 if (ntohs(iph_inner->id) != id)
448 return -EINVAL;
450 return len;
453 static void handle_ipv4(uint8_t *packet, size_t len __maybe_unused,
454 int dns_resolv, int latitude)
456 char hbuff[NI_MAXHOST];
457 struct iphdr *iph = (struct iphdr *) packet;
458 struct sockaddr_in sd;
459 struct hostent *hent;
460 const char *as, *country;
461 char *city;
463 memset(hbuff, 0, sizeof(hbuff));
464 memset(&sd, 0, sizeof(sd));
465 sd.sin_family = PF_INET;
466 sd.sin_addr.s_addr = iph->saddr;
468 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
469 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
471 as = geoip4_as_name(&sd);
472 country = geoip4_country_name(&sd);
473 city = geoip4_city_name(&sd);
475 if (dns_resolv) {
476 hent = gethostbyaddr(&sd.sin_addr, sizeof(sd.sin_addr), PF_INET);
477 if (hent)
478 printf(" %s (%s)", hent->h_name, hbuff);
479 else
480 printf(" %s", hbuff);
481 } else {
482 printf(" %s", hbuff);
484 if (as)
485 printf(" in %s", as);
486 if (country) {
487 printf(" in %s", country);
488 if (city)
489 printf(", %s", city);
491 if (latitude)
492 printf(" (%f/%f)", geoip4_latitude(&sd), geoip4_longitude(&sd));
494 free(city);
497 static int check_ipv6(uint8_t *packet, size_t len, int ttl __maybe_unused,
498 int id, const struct sockaddr *ss)
500 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
501 struct ip6_hdr *ip6h_inner;
502 struct icmp6hdr *icmp6h;
504 if (ip6h->ip6_nxt != 0x3a)
505 return -EINVAL;
506 if (memcmp(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
507 ss)->sin6_addr), sizeof(ip6h->ip6_dst)))
508 return -EINVAL;
510 icmp6h = (struct icmp6hdr *) (packet + sizeof(*ip6h));
511 if (icmp6h->icmp6_type != ICMPV6_TIME_EXCEED)
512 return -EINVAL;
513 if (icmp6h->icmp6_code != ICMPV6_EXC_HOPLIMIT)
514 return -EINVAL;
516 ip6h_inner = (struct ip6_hdr *) (packet + sizeof(*ip6h) + sizeof(*icmp6h));
517 if ((ntohl(ip6h_inner->ip6_flow) & 0x000fffff) != (uint32_t) id)
518 return -EINVAL;
520 return len;
523 static void handle_ipv6(uint8_t *packet, size_t len __maybe_unused,
524 int dns_resolv, int latitude)
526 char hbuff[NI_MAXHOST];
527 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
528 struct sockaddr_in6 sd;
529 struct hostent *hent;
530 const char *as, *country;
531 char *city;
533 memset(hbuff, 0, sizeof(hbuff));
534 memset(&sd, 0, sizeof(sd));
535 sd.sin6_family = PF_INET6;
536 memcpy(&sd.sin6_addr, &ip6h->ip6_src, sizeof(ip6h->ip6_src));
538 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
539 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
541 as = geoip6_as_name(&sd);
542 country = geoip6_country_name(&sd);
543 city = geoip6_city_name(&sd);
545 if (dns_resolv) {
546 hent = gethostbyaddr(&sd.sin6_addr, sizeof(sd.sin6_addr), PF_INET6);
547 if (hent)
548 printf(" %s (%s)", hent->h_name, hbuff);
549 else
550 printf(" %s", hbuff);
551 } else {
552 printf(" %s", hbuff);
554 if (as)
555 printf(" in %s", as);
556 if (country) {
557 printf(" in %s", country);
558 if (city)
559 printf(", %s", city);
561 if (latitude)
562 printf(" (%f/%f)", geoip6_latitude(&sd), geoip6_longitude(&sd));
564 free(city);
567 static void show_trace_info(struct ctx *ctx, const struct sockaddr_storage *ss,
568 const struct sockaddr_storage *sd)
570 char hbuffs[256], hbuffd[256];
572 memset(hbuffd, 0, sizeof(hbuffd));
573 getnameinfo((struct sockaddr *) sd, sizeof(*sd),
574 hbuffd, sizeof(hbuffd), NULL, 0, NI_NUMERICHOST);
576 memset(hbuffs, 0, sizeof(hbuffs));
577 getnameinfo((struct sockaddr *) ss, sizeof(*ss),
578 hbuffs, sizeof(hbuffs), NULL, 0, NI_NUMERICHOST);
580 printf("AS path IPv%d TCP trace from %s to %s:%s (%s) with len %zu "
581 "Bytes, %u max hops\n", ctx->proto == IPPROTO_IP ? 4 : 6,
582 hbuffs, hbuffd, ctx->port, ctx->host, ctx->totlen, ctx->max_ttl);
584 printf("Using flags SYN:%d,ACK:%d,ECN:%d,FIN:%d,PSH:%d,RST:%d,URG:%d\n",
585 ctx->syn, ctx->ack, ctx->ecn, ctx->fin, ctx->psh, ctx->rst, ctx->urg);
587 if (ctx->payload)
588 printf("With payload: \'%s\'\n", ctx->payload);
591 static int get_remote_fd(struct ctx *ctx, struct sockaddr_storage *ss,
592 struct sockaddr_storage *sd)
594 int fd = -1, ret, one = 1, af = AF_INET;
595 struct addrinfo hints, *ahead, *ai;
596 unsigned char bind_ip[sizeof(struct in6_addr)];
598 memset(&hints, 0, sizeof(hints));
599 hints.ai_family = PF_UNSPEC;
600 hints.ai_socktype = SOCK_STREAM;
601 hints.ai_protocol = IPPROTO_TCP;
602 hints.ai_flags = AI_NUMERICSERV;
604 ret = getaddrinfo(ctx->host, ctx->port, &hints, &ahead);
605 if (ret < 0)
606 panic("Cannot get address info!\n");
608 for (ai = ahead; ai != NULL && fd < 0; ai = ai->ai_next) {
609 if (!((ai->ai_family == PF_INET6 && ctx->proto == IPPROTO_IPV6) ||
610 (ai->ai_family == PF_INET && ctx->proto == IPPROTO_IP)))
611 continue;
613 fd = socket(ai->ai_family, SOCK_RAW, IPPROTO_RAW);
614 if (fd < 0)
615 continue;
617 memset(ss, 0, sizeof(*ss));
618 ret = device_address(ctx->dev, ai->ai_family, ss);
619 if (ret < 0 && !ctx->bind_addr)
620 panic("Cannot get own device address!\n");
622 if (ctx->bind_addr) {
623 if (ctx->proto == IPPROTO_IPV6)
624 af = AF_INET6;
626 if (inet_pton(af, ctx->bind_addr, &bind_ip) != 1)
627 panic("Address is invalid!\n");
629 if (af == AF_INET6) {
630 struct sockaddr_in6 *ss6 = (struct sockaddr_in6 *) ss;
631 memcpy(&ss6->sin6_addr.s6_addr, &bind_ip, sizeof(struct in6_addr));
632 } else {
633 struct sockaddr_in *ss4 = (struct sockaddr_in *) ss;
634 memcpy(&ss4->sin_addr.s_addr, &bind_ip, sizeof(struct in_addr));
638 ret = bind(fd, (struct sockaddr *) ss, sizeof(*ss));
639 if (ret < 0)
640 panic("Cannot bind socket!\n");
642 memset(sd, 0, sizeof(*sd));
643 memcpy(sd, ai->ai_addr, ai->ai_addrlen);
645 ctx->sd_len = ai->ai_addrlen;
646 ctx->dport = strtoul(ctx->port, NULL, 10);
648 ret = setsockopt(fd, ctx->proto, IP_HDRINCL, &one, sizeof(one));
649 if (ret < 0)
650 panic("Kernel does not support IP_HDRINCL!\n");
652 if (ai->ai_family == PF_INET6) {
653 struct sockaddr_in6 *sd6 = (struct sockaddr_in6 *) sd;
655 sd6->sin6_port = 0;
658 break;
661 freeaddrinfo(ahead);
663 if (fd < 0)
664 panic("Cannot create socket! Does remote "
665 "support IPv%d?!\n",
666 ctx->proto == IPPROTO_IP ? 4 : 6);
668 return fd;
671 static void inject_filter(struct ctx *ctx, int fd)
673 struct sock_fprog bpf_ops;
675 enable_kernel_bpf_jit_compiler();
677 memset(&bpf_ops, 0, sizeof(bpf_ops));
678 bpf_ops.filter = (struct sock_filter *) af_ops[ctx->proto].filter;
679 bpf_ops.len = af_ops[ctx->proto].flen;
681 bpf_attach_to_sock(fd, &bpf_ops);
684 static int __process_node(struct ctx *ctx, int fd, int fd_cap, int ttl,
685 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
686 const struct sockaddr_storage *ss,
687 const struct sockaddr_storage *sd, struct timeval *diff)
689 int pkt_id, ret, timeout;
690 struct pollfd pfd;
691 struct timeval start, end;
693 prepare_polling(fd_cap, &pfd);
695 memset(pkt_snd, 0, ctx->totlen);
696 pkt_id = af_ops[ctx->proto].assembler(pkt_snd, ctx->totlen, ttl,
697 inner_proto, ctx,
698 (const struct sockaddr *) sd,
699 (const struct sockaddr *) ss);
701 ret = sendto(fd, pkt_snd, ctx->totlen, 0, (struct sockaddr *) sd,
702 ctx->sd_len);
703 if (ret < 0)
704 panic("sendto failed: %s\n", strerror(errno));
706 bug_on(gettimeofday(&start, NULL));
708 timeout = (ctx->timeout > 0 ? ctx->timeout : 2) * 1000;
710 ret = poll(&pfd, 1, timeout);
711 if (ret > 0 && pfd.revents & POLLIN && sigint == 0) {
712 bug_on(gettimeofday(&end, NULL));
713 if (diff)
714 timersub(&end, &start, diff);
716 ret = recvfrom(fd_cap, pkt_rcv, ctx->rcvlen, 0, NULL, NULL);
717 if (ret < (int) (sizeof(struct ethhdr) + af_ops[ctx->proto].min_len_icmp))
718 return -EIO;
720 return af_ops[ctx->proto].check(pkt_rcv + sizeof(struct ethhdr),
721 ret - sizeof(struct ethhdr), ttl,
722 pkt_id, (const struct sockaddr *) ss);
723 } else {
724 return -EIO;
727 return 0;
730 static void timerdiv(const unsigned long divisor, const struct timeval *tv,
731 struct timeval *result)
733 uint64_t x = ((uint64_t) tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
735 result->tv_sec = x / 1000 / 1000;
736 result->tv_usec = x % (1000 * 1000);
739 static int timevalcmp(const void *t1, const void *t2)
741 if (timercmp((struct timeval *) t1, (struct timeval *) t2, <))
742 return -1;
743 if (timercmp((struct timeval *) t1, (struct timeval *) t2, >))
744 return 1;
746 return 0;
749 static const char *proto_short(int proto)
751 switch (proto) {
752 case IPPROTO_TCP:
753 return "t";
754 case IPPROTO_ICMP:
755 case IPPROTO_ICMPV6:
756 return "i";
757 default:
758 return "?";
762 static int __process_time(struct ctx *ctx, int fd, int fd_cap, int ttl,
763 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
764 const struct sockaddr_storage *ss,
765 const struct sockaddr_storage *sd)
767 size_t i, j = 0;
768 int good = 0, ret = -EIO, idx, ret_good = -EIO;
769 struct timeval probes[9], *tmp, sum, res;
770 uint8_t *trash = xmalloc(ctx->rcvlen);
771 char *cwait[] = { "-", "\\", "|", "/" };
773 memset(probes, 0, sizeof(probes));
774 for (i = 0; i < array_size(probes) && sigint == 0; ++i) {
775 ret = __process_node(ctx, fd, fd_cap, ttl, inner_proto,
776 pkt_snd, good == 0 ? pkt_rcv : trash,
777 ss, sd, &probes[i]);
778 if (ret > 0) {
779 if (good == 0)
780 ret_good = ret;
781 good++;
784 if (good == 0 && ctx->queries == (int) i)
785 break;
787 usleep(50000);
789 printf("\r%2d: %s", ttl, cwait[j++]);
790 fflush(stdout);
791 if (j >= array_size(cwait))
792 j = 0;
795 if (good == 0) {
796 xfree(trash);
797 return -EIO;
800 tmp = xcalloc(good, sizeof(struct timeval));
801 for (i = j = 0; i < array_size(probes); ++i) {
802 if (probes[i].tv_sec == 0 && probes[i].tv_usec == 0)
803 continue;
804 tmp[j].tv_sec = probes[i].tv_sec;
805 tmp[j].tv_usec = probes[i].tv_usec;
806 j++;
809 qsort(tmp, j, sizeof(struct timeval), timevalcmp);
811 printf("\r%2d: %s[", ttl, proto_short(inner_proto));
812 idx = j / 2;
813 switch (j % 2) {
814 case 0:
815 timeradd(&tmp[idx], &tmp[idx - 1], &sum);
816 timerdiv(2, &sum, &res);
817 if (res.tv_sec > 0)
818 printf("%lu sec ", res.tv_sec);
819 printf("%7lu us", res.tv_usec);
820 break;
821 case 1:
822 if (tmp[idx].tv_sec > 0)
823 printf("%lu sec ", tmp[idx].tv_sec);
824 printf("%7lu us", tmp[idx].tv_usec);
825 break;
827 printf("]");
829 xfree(tmp);
830 xfree(trash);
832 return ret_good;
835 static int __probe_remote(struct ctx *ctx, int fd, int fd_cap, int ttl,
836 uint8_t *pkt_snd, uint8_t *pkt_rcv,
837 const struct sockaddr_storage *ss,
838 const struct sockaddr_storage *sd,
839 int inner_proto)
841 int ret = -EIO, tries = ctx->queries;
843 while (tries-- > 0 && sigint == 0) {
844 ret = __process_time(ctx, fd, fd_cap, ttl, inner_proto,
845 pkt_snd, pkt_rcv, ss, sd);
846 if (ret < 0)
847 continue;
849 af_ops[ctx->proto].handler(pkt_rcv + sizeof(struct ethhdr),
850 ret - sizeof(struct ethhdr),
851 ctx->dns_resolv, ctx->latitude);
852 if (ctx->show) {
853 struct pkt_buff *pkt;
855 printf("\n");
856 pkt = pkt_alloc(pkt_rcv, ret);
857 hex_ascii(pkt);
858 tprintf_flush();
859 pkt_free(pkt);
862 break;
865 return ret;
868 static int __process_ttl(struct ctx *ctx, int fd, int fd_cap, int ttl,
869 uint8_t *pkt_snd, uint8_t *pkt_rcv,
870 const struct sockaddr_storage *ss,
871 const struct sockaddr_storage *sd)
873 int ret = -EIO;
874 size_t i;
875 const int inner_protos[] = {
876 IPPROTO_TCP,
877 IPPROTO_ICMP,
880 printf("%2d: ", ttl);
881 fflush(stdout);
883 for (i = 0; i < array_size(inner_protos) && sigint == 0; ++i) {
884 ret = __probe_remote(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv, ss, sd,
885 inner_protos[i]);
886 if (ret > 0)
887 break;
890 if (ret <= 0)
891 printf("\r%2d: ?[ no answer]", ttl);
892 if (ctx->show == 0)
893 printf("\n");
894 if (ctx->show && ret <= 0)
895 printf("\n\n");
897 fflush(stdout);
898 return 0;
901 static int main_trace(struct ctx *ctx)
903 int fd, fd_cap, ifindex, ttl;
904 struct ring dummy_ring;
905 struct sockaddr_storage ss, sd;
906 uint8_t *pkt_snd, *pkt_rcv;
908 fd = get_remote_fd(ctx, &ss, &sd);
909 fd_cap = pf_socket();
911 inject_filter(ctx, fd_cap);
913 ifindex = device_ifindex(ctx->dev);
914 bind_ring_generic(fd_cap, &dummy_ring, ifindex, false);
916 if (ctx->totlen < af_ops[ctx->proto].min_len_tcp) {
917 ctx->totlen = af_ops[ctx->proto].min_len_tcp;
918 if (ctx->payload)
919 ctx->totlen += strlen(ctx->payload);
922 ctx->rcvlen = device_mtu(ctx->dev) - sizeof(struct ethhdr);
923 if (ctx->totlen >= ctx->rcvlen)
924 panic("Packet len exceeds device MTU!\n");
926 pkt_snd = xmalloc(ctx->totlen);
927 pkt_rcv = xmalloc(ctx->rcvlen);
929 show_trace_info(ctx, &ss, &sd);
931 for (ttl = ctx->init_ttl; ttl <= ctx->max_ttl && sigint == 0; ++ttl)
932 __process_ttl(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv,
933 &ss, &sd);
935 xfree(pkt_snd);
936 xfree(pkt_rcv);
938 close(fd_cap);
939 close(fd);
941 return 0;
944 int main(int argc, char **argv)
946 int c, ret;
947 struct ctx ctx;
949 setfsuid(getuid());
950 setfsgid(getgid());
952 srand(time(NULL));
954 memset(&ctx, 0, sizeof(ctx));
955 ctx.init_ttl = 1;
956 ctx.max_ttl = 30;
957 ctx.queries = 2;
958 ctx.timeout = 2;
959 ctx.proto = IPPROTO_IP;
960 ctx.payload = NULL;
961 ctx.dev = xstrdup("eth0");
962 ctx.port = xstrdup("80");
963 ctx.bind_addr = NULL;
965 while ((c = getopt_long(argc, argv, short_options, long_options,
966 NULL)) != EOF) {
967 switch (c) {
968 case 'h':
969 help();
970 break;
971 case 'v':
972 version();
973 break;
974 case 'u':
975 update_geoip();
976 die();
977 break;
978 case 'H':
979 ctx.host = xstrdup(optarg);
980 break;
981 case 'p':
982 if (ctx.port)
983 xfree(ctx.port);
984 ctx.port = xstrdup(optarg);
985 break;
986 case 'n':
987 ctx.dns_resolv = 0;
988 break;
989 case '4':
990 ctx.proto = IPPROTO_IP;
991 break;
992 case '6':
993 ctx.proto = IPPROTO_IPV6;
994 break;
995 case 'Z':
996 ctx.show = 1;
997 break;
998 case 'N':
999 ctx.dns_resolv = 1;
1000 break;
1001 case 'f':
1002 ctx.init_ttl = atoi(optarg);
1003 if (ctx.init_ttl <= 0)
1004 help();
1005 break;
1006 case 'm':
1007 ctx.max_ttl = atoi(optarg);
1008 if (ctx.max_ttl <= 0)
1009 help();
1010 break;
1011 case 'b':
1012 ctx.bind_addr = xstrdup(optarg);
1013 break;
1014 case 'i':
1015 case 'd':
1016 free(ctx.dev);
1017 ctx.dev = xstrdup(optarg);
1018 break;
1019 case 'q':
1020 ctx.queries = atoi(optarg);
1021 if (ctx.queries <= 0)
1022 help();
1023 break;
1024 case 'x':
1025 ctx.timeout = atoi(optarg);
1026 if (ctx.timeout <= 0)
1027 help();
1028 break;
1029 case 'L':
1030 ctx.latitude = 1;
1031 break;
1032 case 'S':
1033 ctx.syn = 1;
1034 break;
1035 case 'A':
1036 ctx.ack = 1;
1037 break;
1038 case 'F':
1039 ctx.fin = 1;
1040 break;
1041 case 'U':
1042 ctx.urg = 1;
1043 break;
1044 case 'P':
1045 ctx.psh = 1;
1046 break;
1047 case 'R':
1048 ctx.rst = 1;
1049 break;
1050 case 'E':
1051 ctx.syn = 1;
1052 ctx.ecn = 1;
1053 break;
1054 case 't':
1055 ctx.tos = atoi(optarg);
1056 if (ctx.tos < 0)
1057 help();
1058 break;
1059 case 'G':
1060 ctx.nofrag = 1;
1061 break;
1062 case 'X':
1063 ctx.payload = xstrdup(optarg);
1064 break;
1065 case 'l':
1066 ctx.totlen = strtoul(optarg, NULL, 10);
1067 if (ctx.totlen == 0)
1068 help();
1069 break;
1070 case '?':
1071 switch (optopt) {
1072 case 'H':
1073 case 'p':
1074 case 'f':
1075 case 'm':
1076 case 'i':
1077 case 'd':
1078 case 'q':
1079 case 'x':
1080 case 'X':
1081 case 't':
1082 case 'l':
1083 panic("Option -%c requires an argument!\n",
1084 optopt);
1085 default:
1086 if (isprint(optopt))
1087 printf("Unknown option character `0x%X\'!\n", optopt);
1088 die();
1090 default:
1091 break;
1095 if (argc < 3 || !ctx.host || !ctx.port || ctx.init_ttl > ctx.max_ttl ||
1096 ctx.init_ttl > MAXTTL || ctx.max_ttl > MAXTTL)
1097 help();
1099 if (!device_up_and_running(ctx.dev))
1100 panic("Networking device not up and running!\n");
1101 if (device_mtu(ctx.dev) <= ctx.totlen)
1102 panic("Packet larger than device MTU!\n");
1104 register_signal(SIGHUP, signal_handler);
1105 register_signal(SIGINT, signal_handler);
1106 register_signal(SIGQUIT, signal_handler);
1107 register_signal(SIGTERM, signal_handler);
1109 tprintf_init();
1110 init_geoip(1);
1112 ret = main_trace(&ctx);
1114 destroy_geoip();
1115 tprintf_cleanup();
1117 free(ctx.dev);
1118 free(ctx.host);
1119 free(ctx.port);
1120 free(ctx.bind_addr);
1121 free(ctx.payload);
1123 return ret;