csum: Remove unnecessary memset in p4_csum()
[netsniff-ng-new.git] / astraceroute.c
bloba801ab16cc2fcba5af73bf618b8b0344e22247c7
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 "config.h"
39 #include "tprintf.h"
40 #include "pkt_buff.h"
41 #include "proto.h"
42 #include "xmalloc.h"
43 #include "csum.h"
44 #include "sock.h"
45 #include "geoip.h"
46 #include "ring.h"
47 #include "built_in.h"
49 struct ctx {
50 char *host, *port, *dev, *payload, *bind_addr;
51 size_t totlen, rcvlen;
52 int init_ttl, max_ttl, dns_resolv, queries, timeout;
53 int syn, ack, ecn, fin, psh, rst, urg, tos, nofrag, proto, show;
54 int sd_len, dport, latitude;
57 struct proto_ops {
58 int (*assembler)(uint8_t *packet, size_t len, int ttl, int proto,
59 const struct ctx *ctx, const struct sockaddr *dst,
60 const struct sockaddr *src);
61 const struct sock_filter *filter;
62 unsigned int flen;
63 size_t min_len_tcp, min_len_icmp;
64 int (*check)(uint8_t *packet, size_t len, int ttl, int id,
65 const struct sockaddr *src);
66 void (*handler)(uint8_t *packet, size_t len, int dns_resolv,
67 int latitude);
70 static sig_atomic_t sigint = 0;
72 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
73 const struct ctx *ctx, const struct sockaddr *dst,
74 const struct sockaddr *src);
75 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
76 const struct ctx *ctx, const struct sockaddr *dst,
77 const struct sockaddr *src);
78 static int check_ipv4(uint8_t *packet, size_t len, int ttl, int id,
79 const struct sockaddr *ss);
80 static void handle_ipv4(uint8_t *packet, size_t len, int dns_resolv,
81 int latitude);
82 static int check_ipv6(uint8_t *packet, size_t len, int ttl, int id,
83 const struct sockaddr *ss);
84 static void handle_ipv6(uint8_t *packet, size_t len, int dns_resolv,
85 int latitude);
87 static const char *short_options = "H:p:nNf:m:b:i:d:q:x:SAEFPURt:Gl:hv46X:ZuL";
88 static const struct option long_options[] = {
89 {"host", required_argument, NULL, 'H'},
90 {"port", required_argument, NULL, 'p'},
91 {"init-ttl", required_argument, NULL, 'f'},
92 {"max-ttl", required_argument, NULL, 'm'},
93 {"bind", required_argument, NULL, 'b'},
94 {"dev", required_argument, NULL, 'd'},
95 {"num-probes", required_argument, NULL, 'q'},
96 {"timeout", required_argument, NULL, 'x'},
97 {"tos", required_argument, NULL, 't'},
98 {"payload", required_argument, NULL, 'X'},
99 {"totlen", required_argument, NULL, 'l'},
100 {"numeric", no_argument, NULL, 'n'},
101 {"latitude", no_argument, NULL, 'L'},
102 {"update", no_argument, NULL, 'u'},
103 {"dns", no_argument, NULL, 'N'},
104 {"ipv4", no_argument, NULL, '4'},
105 {"ipv6", no_argument, NULL, '6'},
106 {"syn", no_argument, NULL, 'S'},
107 {"ack", no_argument, NULL, 'A'},
108 {"urg", no_argument, NULL, 'U'},
109 {"fin", no_argument, NULL, 'F'},
110 {"psh", no_argument, NULL, 'P'},
111 {"rst", no_argument, NULL, 'R'},
112 {"ecn-syn", no_argument, NULL, 'E'},
113 {"show-packet", no_argument, NULL, 'Z'},
114 {"nofrag", no_argument, NULL, 'G'},
115 {"version", no_argument, NULL, 'v'},
116 {"help", no_argument, NULL, 'h'},
117 {NULL, 0, NULL, 0}
120 static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
121 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
122 "Swiss federal institute of technology (ETH Zurich)\n"
123 "License: GNU GPL version 2.0\n"
124 "This is free software: you are free to change and redistribute it.\n"
125 "There is NO WARRANTY, to the extent permitted by law.";
127 static const struct sock_filter ipv4_icmp_type_11[] = {
128 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
129 { 0x15, 0, 8, 0x00000800 }, /* jneq #0x800, drop */
130 { 0x30, 0, 0, 0x00000017 }, /* ldb [23] */
131 { 0x15, 0, 6, 0x00000001 }, /* jneq #0x1, drop */
132 { 0x28, 0, 0, 0x00000014 }, /* ldh [20] */
133 { 0x45, 4, 0, 0x00001fff }, /* jset #0x1fff, drop */
134 { 0xb1, 0, 0, 0x0000000e }, /* ldxb 4*([14]&0xf) */
135 { 0x50, 0, 0, 0x0000000e }, /* ldb [x + 14] */
136 { 0x15, 0, 1, 0x0000000b }, /* jneq #0xb, drop */
137 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
138 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
141 static const struct sock_filter ipv6_icmp6_type_3[] = {
142 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
143 { 0x15, 0, 5, 0x000086dd }, /* jneq #0x86dd, drop */
144 { 0x30, 0, 0, 0x00000014 }, /* ldb [20] */
145 { 0x15, 0, 3, 0x0000003a }, /* jneq #0x3a, drop */
146 { 0x30, 0, 0, 0x00000036 }, /* ldb [54] */
147 { 0x15, 0, 1, 0x00000003 }, /* jneq #0x3, drop */
148 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
149 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
152 static const struct proto_ops af_ops[] = {
153 [IPPROTO_IP] = {
154 .assembler = assemble_ipv4,
155 .handler = handle_ipv4,
156 .check = check_ipv4,
157 .filter = ipv4_icmp_type_11,
158 .flen = array_size(ipv4_icmp_type_11),
159 .min_len_tcp = sizeof(struct iphdr) + sizeof(struct tcphdr),
160 .min_len_icmp = sizeof(struct iphdr) + sizeof(struct icmphdr),
162 [IPPROTO_IPV6] = {
163 .assembler = assemble_ipv6,
164 .handler = handle_ipv6,
165 .check = check_ipv6,
166 .filter = ipv6_icmp6_type_3,
167 .flen = array_size(ipv6_icmp6_type_3),
168 .min_len_tcp = sizeof(struct ip6_hdr) + sizeof(struct tcphdr),
169 .min_len_icmp = sizeof(struct ip6_hdr) + sizeof(struct icmp6hdr),
173 static void signal_handler(int number)
175 switch (number) {
176 case SIGINT:
177 case SIGQUIT:
178 case SIGTERM:
179 sigint = 1;
180 default:
181 break;
185 static void __noreturn help(void)
187 printf("astraceroute %s, autonomous system trace route utility\n", VERSION_STRING);
188 puts("http://www.netsniff-ng.org\n\n"
189 "Usage: astraceroute [options]\n"
190 "Options:\n"
191 " -H|--host <host> Host/IPv4/IPv6 to lookup AS route to\n"
192 " -p|--port <port> Hosts port to lookup AS route to\n"
193 " -i|-d|--dev <device> Networking device, e.g. eth0\n"
194 " -b|--bind <IP> IP address to bind to, Must specify -6 for an IPv6 address\n"
195 " -f|--init-ttl <ttl> Set initial TTL\n"
196 " -m|--max-ttl <ttl> Set maximum TTL (def: 30)\n"
197 " -q|--num-probes <num> Number of max probes for each hop (def: 2)\n"
198 " -x|--timeout <sec> Probe response timeout in sec (def: 3)\n"
199 " -X|--payload <string> Specify a payload string to test DPIs\n"
200 " -l|--totlen <len> Specify total packet len\n"
201 " -4|--ipv4 Use IPv4-only requests\n"
202 " -6|--ipv6 Use IPv6-only requests\n"
203 " -n|--numeric Do not do reverse DNS lookup for hops\n"
204 " -u|--update Update GeoIP databases\n"
205 " -L|--latitude Show latitude and longitude\n"
206 " -N|--dns Do a reverse DNS lookup for hops\n"
207 " -S|--syn Set TCP SYN flag\n"
208 " -A|--ack Set TCP ACK flag\n"
209 " -F|--fin Set TCP FIN flag\n"
210 " -P|--psh Set TCP PSH flag\n"
211 " -U|--urg Set TCP URG flag\n"
212 " -R|--rst Set TCP RST flag\n"
213 " -E|--ecn-syn Send ECN SYN packets (RFC3168)\n"
214 " -t|--tos <tos> Set the IP TOS field\n"
215 " -G|--nofrag Set do not fragment bit\n"
216 " -Z|--show-packet Show returned packet on each hop\n"
217 " -v|--version Print version and exit\n"
218 " -h|--help Print this help and exit\n\n"
219 "Examples:\n"
220 " IPv4 trace of AS with TCP SYN probe (this will most-likely pass):\n"
221 " astraceroute -i eth0 -N -S -H netsniff-ng.org\n"
222 " IPv4 trace of AS with TCP ECN SYN probe:\n"
223 " astraceroute -i eth0 -N -E -H netsniff-ng.org\n"
224 " IPv4 trace of AS with TCP FIN probe:\n"
225 " astraceroute -i eth0 -N -F -H netsniff-ng.org\n"
226 " IPv4 trace of AS with Xmas probe:\n"
227 " astraceroute -i eth0 -N -FPU -H netsniff-ng.org\n"
228 " IPv4 trace of AS with Null probe with ASCII payload:\n"
229 " astraceroute -i eth0 -N -H netsniff-ng.org -X \"censor-me\" -Z\n"
230 " IPv6 trace of AS up to www.6bone.net:\n"
231 " astraceroute -6 -i eth0 -S -E -N -H www.6bone.net\n\n"
232 "Note:\n"
233 " If the TCP probe did not give any results, then astraceroute will\n"
234 " automatically probe for classic ICMP packets! To gather more\n"
235 " information about astraceroute's fetched AS numbers, see e.g.\n"
236 " http://bgp.he.net/AS<number>!\n");
237 puts(copyright);
238 die();
241 static void __noreturn version(void)
243 printf("astraceroute %s, Git id: %s\n", VERSION_LONG, GITVERSION);
244 puts("autonomous system trace route utility\n"
245 "http://www.netsniff-ng.org\n");
246 puts(copyright);
247 die();
250 static void __assemble_data(uint8_t *packet, size_t len, const char *payload)
252 size_t i;
254 if (payload == NULL) {
255 for (i = 0; i < len; ++i)
256 packet[i] = (uint8_t) rand();
257 } else {
258 size_t lmin = min(len, strlen(payload));
260 for (i = 0; i < lmin; ++i)
261 packet[i] = (uint8_t) payload[i];
262 for (i = lmin; i < len; ++i)
263 packet[i] = (uint8_t) rand();
267 static void __assemble_icmp4(uint8_t *packet, size_t len)
269 struct icmphdr *icmph = (struct icmphdr *) packet;
271 bug_on(len < sizeof(struct icmphdr));
273 icmph->type = ICMP_ECHO;
274 icmph->code = 0;
275 icmph->checksum = 0;
278 static void __assemble_icmp6(uint8_t *packet, size_t len)
280 struct icmp6hdr *icmp6h = (struct icmp6hdr *) packet;
282 bug_on(len < sizeof(struct icmp6hdr));
284 icmp6h->icmp6_type = ICMPV6_ECHO_REQUEST;
285 icmp6h->icmp6_code = 0;
286 icmp6h->icmp6_cksum = 0;
289 static void __assemble_tcp(uint8_t *packet, size_t len, int syn, int ack,
290 int urg, int fin, int rst, int psh, int ecn,
291 int dport)
293 struct tcphdr *tcph = (struct tcphdr *) packet;
295 bug_on(len < sizeof(struct tcphdr));
297 tcph->source = htons((uint16_t) rand());
298 tcph->dest = htons((uint16_t) dport);
300 tcph->seq = htonl(rand());
301 tcph->ack_seq = (!!ack ? htonl(rand()) : 0);
303 tcph->doff = 5;
305 tcph->syn = !!syn;
306 tcph->ack = !!ack;
307 tcph->urg = !!urg;
308 tcph->fin = !!fin;
309 tcph->rst = !!rst;
310 tcph->psh = !!psh;
311 tcph->ece = !!ecn;
312 tcph->cwr = !!ecn;
314 tcph->window = htons((uint16_t) (100 + (rand() % 65435)));
315 tcph->urg_ptr = (!!urg ? htons((uint16_t) rand()) : 0);
316 tcph->check = 0;
319 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
320 const struct ctx *ctx, const struct sockaddr *dst,
321 const struct sockaddr *src)
323 uint8_t *data;
324 size_t data_len, off_next = 0;
325 struct iphdr *iph = (struct iphdr *) packet;
327 bug_on(!src || !dst);
328 bug_on(src->sa_family != PF_INET || dst->sa_family != PF_INET);
329 bug_on(len < sizeof(*iph) + min(sizeof(struct tcphdr),
330 sizeof(struct icmphdr)));
332 iph->ihl = 5;
333 iph->version = 4;
334 iph->tos = (uint8_t) ctx->tos;
336 iph->tot_len = htons((uint16_t) len);
337 iph->id = htons((uint16_t) rand());
339 iph->frag_off = ctx->nofrag ? IP_DF : 0;
340 iph->ttl = (uint8_t) ttl;
342 iph->saddr = ((const struct sockaddr_in *) src)->sin_addr.s_addr;
343 iph->daddr = ((const struct sockaddr_in *) dst)->sin_addr.s_addr;
345 iph->protocol = (uint8_t) proto;
347 data = packet + sizeof(*iph);
348 data_len = len - sizeof(*iph);
350 switch (proto) {
351 case IPPROTO_TCP:
352 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
353 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
354 off_next = sizeof(struct tcphdr);
355 break;
356 case IPPROTO_ICMP:
357 __assemble_icmp4(data, data_len);
358 off_next = sizeof(struct icmphdr);
359 break;
360 default:
361 bug();
364 data = packet + sizeof(*iph) + off_next;
365 data_len = len - sizeof(*iph) - off_next;
367 __assemble_data(data, data_len, ctx->payload);
369 iph->check = csum((unsigned short *) packet, ntohs(iph->tot_len) >> 1);
371 return ntohs(iph->id);
374 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
375 const struct ctx *ctx, const struct sockaddr *dst,
376 const struct sockaddr *src)
378 uint8_t *data;
379 size_t data_len, off_next = 0;
380 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
382 bug_on(!src || !dst);
383 bug_on(src->sa_family != PF_INET6 || dst->sa_family != PF_INET6);
384 bug_on(len < sizeof(*ip6h) + min(sizeof(struct tcphdr),
385 sizeof(struct icmp6hdr)));
387 ip6h->ip6_flow = htonl(rand() & 0x000fffff);
388 ip6h->ip6_vfc = 0x60;
390 ip6h->ip6_plen = htons((uint16_t) len - sizeof(*ip6h));
391 ip6h->ip6_nxt = (uint8_t) proto;
392 ip6h->ip6_hlim = (uint8_t) ttl;
394 memcpy(&ip6h->ip6_src, &(((const struct sockaddr_in6 *)
395 src)->sin6_addr), sizeof(ip6h->ip6_src));
396 memcpy(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
397 dst)->sin6_addr), sizeof(ip6h->ip6_dst));
399 data = packet + sizeof(*ip6h);
400 data_len = len - sizeof(*ip6h);
402 switch (proto) {
403 case IPPROTO_TCP:
404 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
405 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
406 off_next = sizeof(struct tcphdr);
407 break;
408 case IPPROTO_ICMP:
409 case IPPROTO_ICMPV6:
410 __assemble_icmp6(data, data_len);
411 off_next = sizeof(struct icmp6hdr);
412 break;
413 default:
414 bug();
417 data = packet + sizeof(*ip6h) + off_next;
418 data_len = len - sizeof(*ip6h) - off_next;
420 __assemble_data(data, data_len, ctx->payload);
422 return ntohl(ip6h->ip6_flow) & 0x000fffff;
425 static int check_ipv4(uint8_t *packet, size_t len, int ttl __maybe_unused,
426 int id, const struct sockaddr *ss)
428 struct iphdr *iph = (struct iphdr *) packet;
429 struct iphdr *iph_inner;
430 struct icmphdr *icmph;
432 if (iph->protocol != IPPROTO_ICMP)
433 return -EINVAL;
434 if (iph->daddr != ((const struct sockaddr_in *) ss)->sin_addr.s_addr)
435 return -EINVAL;
437 icmph = (struct icmphdr *) (packet + sizeof(struct iphdr));
438 if (icmph->type != ICMP_TIME_EXCEEDED)
439 return -EINVAL;
440 if (icmph->code != ICMP_EXC_TTL)
441 return -EINVAL;
443 iph_inner = (struct iphdr *) (packet + sizeof(struct iphdr) +
444 sizeof(struct icmphdr));
445 if (ntohs(iph_inner->id) != id)
446 return -EINVAL;
448 return len;
451 static void handle_ipv4(uint8_t *packet, size_t len __maybe_unused,
452 int dns_resolv, int latitude)
454 char hbuff[NI_MAXHOST];
455 struct iphdr *iph = (struct iphdr *) packet;
456 struct sockaddr_in sd;
457 struct hostent *hent;
458 const char *as, *country, *city;
460 memset(hbuff, 0, sizeof(hbuff));
461 memset(&sd, 0, sizeof(sd));
462 sd.sin_family = PF_INET;
463 sd.sin_addr.s_addr = iph->saddr;
465 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
466 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
468 as = geoip4_as_name(&sd);
469 country = geoip4_country_name(&sd);
470 city = geoip4_city_name(&sd);
472 if (dns_resolv) {
473 hent = gethostbyaddr(&sd.sin_addr, sizeof(sd.sin_addr), PF_INET);
474 if (hent)
475 printf(" %s (%s)", hent->h_name, hbuff);
476 else
477 printf(" %s", hbuff);
478 } else {
479 printf(" %s", hbuff);
481 if (as)
482 printf(" in %s", as);
483 if (country) {
484 printf(" in %s", country);
485 if (city)
486 printf(", %s", city);
488 if (latitude)
489 printf(" (%f/%f)", geoip4_latitude(&sd), geoip4_longitude(&sd));
492 static int check_ipv6(uint8_t *packet, size_t len, int ttl __maybe_unused,
493 int id, const struct sockaddr *ss)
495 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
496 struct ip6_hdr *ip6h_inner;
497 struct icmp6hdr *icmp6h;
499 if (ip6h->ip6_nxt != 0x3a)
500 return -EINVAL;
501 if (memcmp(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
502 ss)->sin6_addr), sizeof(ip6h->ip6_dst)))
503 return -EINVAL;
505 icmp6h = (struct icmp6hdr *) (packet + sizeof(*ip6h));
506 if (icmp6h->icmp6_type != ICMPV6_TIME_EXCEED)
507 return -EINVAL;
508 if (icmp6h->icmp6_code != ICMPV6_EXC_HOPLIMIT)
509 return -EINVAL;
511 ip6h_inner = (struct ip6_hdr *) (packet + sizeof(*ip6h) + sizeof(*icmp6h));
512 if ((ntohl(ip6h_inner->ip6_flow) & 0x000fffff) != (uint32_t) id)
513 return -EINVAL;
515 return len;
518 static void handle_ipv6(uint8_t *packet, size_t len __maybe_unused,
519 int dns_resolv, int latitude)
521 char hbuff[NI_MAXHOST];
522 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
523 struct sockaddr_in6 sd;
524 struct hostent *hent;
525 const char *as, *country, *city;
527 memset(hbuff, 0, sizeof(hbuff));
528 memset(&sd, 0, sizeof(sd));
529 sd.sin6_family = PF_INET6;
530 memcpy(&sd.sin6_addr, &ip6h->ip6_src, sizeof(ip6h->ip6_src));
532 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
533 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
535 as = geoip6_as_name(&sd);
536 country = geoip6_country_name(&sd);
537 city = geoip6_city_name(&sd);
539 if (dns_resolv) {
540 hent = gethostbyaddr(&sd.sin6_addr, sizeof(sd.sin6_addr), PF_INET6);
541 if (hent)
542 printf(" %s (%s)", hent->h_name, hbuff);
543 else
544 printf(" %s", hbuff);
545 } else {
546 printf(" %s", hbuff);
548 if (as)
549 printf(" in %s", as);
550 if (country) {
551 printf(" in %s", country);
552 if (city)
553 printf(", %s", city);
555 if (latitude)
556 printf(" (%f/%f)", geoip6_latitude(&sd), geoip6_longitude(&sd));
559 static void show_trace_info(struct ctx *ctx, const struct sockaddr_storage *ss,
560 const struct sockaddr_storage *sd)
562 char hbuffs[256], hbuffd[256];
564 memset(hbuffd, 0, sizeof(hbuffd));
565 getnameinfo((struct sockaddr *) sd, sizeof(*sd),
566 hbuffd, sizeof(hbuffd), NULL, 0, NI_NUMERICHOST);
568 memset(hbuffs, 0, sizeof(hbuffs));
569 getnameinfo((struct sockaddr *) ss, sizeof(*ss),
570 hbuffs, sizeof(hbuffs), NULL, 0, NI_NUMERICHOST);
572 printf("AS path IPv%d TCP trace from %s to %s:%s (%s) with len %zu "
573 "Bytes, %u max hops\n", ctx->proto == IPPROTO_IP ? 4 : 6,
574 hbuffs, hbuffd, ctx->port, ctx->host, ctx->totlen, ctx->max_ttl);
576 printf("Using flags SYN:%d,ACK:%d,ECN:%d,FIN:%d,PSH:%d,RST:%d,URG:%d\n",
577 ctx->syn, ctx->ack, ctx->ecn, ctx->fin, ctx->psh, ctx->rst, ctx->urg);
579 if (ctx->payload)
580 printf("With payload: \'%s\'\n", ctx->payload);
583 static int get_remote_fd(struct ctx *ctx, struct sockaddr_storage *ss,
584 struct sockaddr_storage *sd)
586 int fd = -1, ret, one = 1, af = AF_INET;
587 struct addrinfo hints, *ahead, *ai;
588 unsigned char bind_ip[sizeof(struct in6_addr)];
590 memset(&hints, 0, sizeof(hints));
591 hints.ai_family = PF_UNSPEC;
592 hints.ai_socktype = SOCK_STREAM;
593 hints.ai_protocol = IPPROTO_TCP;
594 hints.ai_flags = AI_NUMERICSERV;
596 ret = getaddrinfo(ctx->host, ctx->port, &hints, &ahead);
597 if (ret < 0)
598 panic("Cannot get address info!\n");
600 for (ai = ahead; ai != NULL && fd < 0; ai = ai->ai_next) {
601 if (!((ai->ai_family == PF_INET6 && ctx->proto == IPPROTO_IPV6) ||
602 (ai->ai_family == PF_INET && ctx->proto == IPPROTO_IP)))
603 continue;
605 fd = socket(ai->ai_family, SOCK_RAW, IPPROTO_RAW);
606 if (fd < 0)
607 continue;
609 memset(ss, 0, sizeof(*ss));
610 ret = device_address(ctx->dev, ai->ai_family, ss);
611 if (ret < 0 && !ctx->bind_addr)
612 panic("Cannot get own device address!\n");
614 if (ctx->bind_addr) {
615 if (ctx->proto == IPPROTO_IPV6)
616 af = AF_INET6;
618 if (inet_pton(af, ctx->bind_addr, &bind_ip) != 1)
619 panic("Address is invalid!\n");
621 if (af == AF_INET6) {
622 struct sockaddr_in6 *ss6 = (struct sockaddr_in6 *) ss;
623 memcpy(&ss6->sin6_addr.s6_addr, &bind_ip, sizeof(struct in6_addr));
624 } else {
625 struct sockaddr_in *ss4 = (struct sockaddr_in *) ss;
626 memcpy(&ss4->sin_addr.s_addr, &bind_ip, sizeof(struct in_addr));
630 ret = bind(fd, (struct sockaddr *) ss, sizeof(*ss));
631 if (ret < 0)
632 panic("Cannot bind socket!\n");
634 memset(sd, 0, sizeof(*sd));
635 memcpy(sd, ai->ai_addr, ai->ai_addrlen);
637 ctx->sd_len = ai->ai_addrlen;
638 ctx->dport = strtoul(ctx->port, NULL, 10);
640 ret = setsockopt(fd, ctx->proto, IP_HDRINCL, &one, sizeof(one));
641 if (ret < 0)
642 panic("Kernel does not support IP_HDRINCL!\n");
644 if (ai->ai_family == PF_INET6) {
645 struct sockaddr_in6 *sd6 = (struct sockaddr_in6 *) sd;
647 sd6->sin6_port = 0;
650 break;
653 freeaddrinfo(ahead);
655 if (fd < 0)
656 panic("Cannot create socket! Does remote "
657 "support IPv%d?!\n",
658 ctx->proto == IPPROTO_IP ? 4 : 6);
660 return fd;
663 static void inject_filter(struct ctx *ctx, int fd)
665 struct sock_fprog bpf_ops;
667 enable_kernel_bpf_jit_compiler();
669 memset(&bpf_ops, 0, sizeof(bpf_ops));
670 bpf_ops.filter = (struct sock_filter *) af_ops[ctx->proto].filter;
671 bpf_ops.len = af_ops[ctx->proto].flen;
673 bpf_attach_to_sock(fd, &bpf_ops);
676 static int __process_node(struct ctx *ctx, int fd, int fd_cap, int ttl,
677 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
678 const struct sockaddr_storage *ss,
679 const struct sockaddr_storage *sd, struct timeval *diff)
681 int pkt_id, ret, timeout;
682 struct pollfd pfd;
683 struct timeval start, end;
685 prepare_polling(fd_cap, &pfd);
687 memset(pkt_snd, 0, ctx->totlen);
688 pkt_id = af_ops[ctx->proto].assembler(pkt_snd, ctx->totlen, ttl,
689 inner_proto, ctx,
690 (const struct sockaddr *) sd,
691 (const struct sockaddr *) ss);
693 ret = sendto(fd, pkt_snd, ctx->totlen, 0, (struct sockaddr *) sd,
694 ctx->sd_len);
695 if (ret < 0)
696 panic("sendto failed: %s\n", strerror(errno));
698 bug_on(gettimeofday(&start, NULL));
700 timeout = (ctx->timeout > 0 ? ctx->timeout : 2) * 1000;
702 ret = poll(&pfd, 1, timeout);
703 if (ret > 0 && pfd.revents & POLLIN && sigint == 0) {
704 bug_on(gettimeofday(&end, NULL));
705 if (diff)
706 timersub(&end, &start, diff);
708 ret = recvfrom(fd_cap, pkt_rcv, ctx->rcvlen, 0, NULL, NULL);
709 if (ret < (int) (sizeof(struct ethhdr) + af_ops[ctx->proto].min_len_icmp))
710 return -EIO;
712 return af_ops[ctx->proto].check(pkt_rcv + sizeof(struct ethhdr),
713 ret - sizeof(struct ethhdr), ttl,
714 pkt_id, (const struct sockaddr *) ss);
715 } else {
716 return -EIO;
719 return 0;
722 static void timerdiv(const unsigned long divisor, const struct timeval *tv,
723 struct timeval *result)
725 uint64_t x = ((uint64_t) tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
727 result->tv_sec = x / 1000 / 1000;
728 result->tv_usec = x % (1000 * 1000);
731 static int timevalcmp(const void *t1, const void *t2)
733 if (timercmp((struct timeval *) t1, (struct timeval *) t2, <))
734 return -1;
735 if (timercmp((struct timeval *) t1, (struct timeval *) t2, >))
736 return 1;
738 return 0;
741 static int __process_time(struct ctx *ctx, int fd, int fd_cap, int ttl,
742 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
743 const struct sockaddr_storage *ss,
744 const struct sockaddr_storage *sd)
746 size_t i, j = 0;
747 int good = 0, ret = -EIO, idx, ret_good = -EIO;
748 struct timeval probes[9], *tmp, sum, res;
749 uint8_t *trash = xmalloc(ctx->rcvlen);
750 char *cwait[] = { "-", "\\", "|", "/" };
751 const char *proto_short[] = {
752 [IPPROTO_TCP] = "t",
753 [IPPROTO_ICMP] = "i",
754 [IPPROTO_ICMPV6] = "i",
757 memset(probes, 0, sizeof(probes));
758 for (i = 0; i < array_size(probes) && sigint == 0; ++i) {
759 ret = __process_node(ctx, fd, fd_cap, ttl, inner_proto,
760 pkt_snd, good == 0 ? pkt_rcv : trash,
761 ss, sd, &probes[i]);
762 if (ret > 0) {
763 if (good == 0)
764 ret_good = ret;
765 good++;
768 if (good == 0 && ctx->queries == (int) i)
769 break;
771 usleep(50000);
773 printf("\r%2d: %s", ttl, cwait[j++]);
774 fflush(stdout);
775 if (j >= array_size(cwait))
776 j = 0;
779 if (good == 0) {
780 xfree(trash);
781 return -EIO;
784 tmp = xcalloc(good, sizeof(struct timeval));
785 for (i = j = 0; i < array_size(probes); ++i) {
786 if (probes[i].tv_sec == 0 && probes[i].tv_usec == 0)
787 continue;
788 tmp[j].tv_sec = probes[i].tv_sec;
789 tmp[j].tv_usec = probes[i].tv_usec;
790 j++;
793 qsort(tmp, j, sizeof(struct timeval), timevalcmp);
795 printf("\r%2d: %s[", ttl, proto_short[inner_proto]);
796 idx = j / 2;
797 switch (j % 2) {
798 case 0:
799 timeradd(&tmp[idx], &tmp[idx - 1], &sum);
800 timerdiv(2, &sum, &res);
801 if (res.tv_sec > 0)
802 printf("%lu sec ", res.tv_sec);
803 printf("%7lu us", res.tv_usec);
804 break;
805 case 1:
806 if (tmp[idx].tv_sec > 0)
807 printf("%lu sec ", tmp[idx].tv_sec);
808 printf("%7lu us", tmp[idx].tv_usec);
809 break;
811 printf("]");
813 xfree(tmp);
814 xfree(trash);
816 return ret_good;
819 static int __probe_remote(struct ctx *ctx, int fd, int fd_cap, int ttl,
820 uint8_t *pkt_snd, uint8_t *pkt_rcv,
821 const struct sockaddr_storage *ss,
822 const struct sockaddr_storage *sd,
823 int inner_proto)
825 int ret = -EIO, tries = ctx->queries;
827 while (tries-- > 0 && sigint == 0) {
828 ret = __process_time(ctx, fd, fd_cap, ttl, inner_proto,
829 pkt_snd, pkt_rcv, ss, sd);
830 if (ret < 0)
831 continue;
833 af_ops[ctx->proto].handler(pkt_rcv + sizeof(struct ethhdr),
834 ret - sizeof(struct ethhdr),
835 ctx->dns_resolv, ctx->latitude);
836 if (ctx->show) {
837 struct pkt_buff *pkt;
839 printf("\n");
840 pkt = pkt_alloc(pkt_rcv, ret);
841 hex_ascii(pkt);
842 tprintf_flush();
843 pkt_free(pkt);
846 break;
849 return ret;
852 static int __process_ttl(struct ctx *ctx, int fd, int fd_cap, int ttl,
853 uint8_t *pkt_snd, uint8_t *pkt_rcv,
854 const struct sockaddr_storage *ss,
855 const struct sockaddr_storage *sd)
857 int ret = -EIO;
858 size_t i;
859 const int inner_protos[] = {
860 IPPROTO_TCP,
861 IPPROTO_ICMP,
864 printf("%2d: ", ttl);
865 fflush(stdout);
867 for (i = 0; i < array_size(inner_protos) && sigint == 0; ++i) {
868 ret = __probe_remote(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv, ss, sd,
869 inner_protos[i]);
870 if (ret > 0)
871 break;
874 if (ret <= 0)
875 printf("\r%2d: ?[ no answer]", ttl);
876 if (ctx->show == 0)
877 printf("\n");
878 if (ctx->show && ret <= 0)
879 printf("\n\n");
881 fflush(stdout);
882 return 0;
885 static int main_trace(struct ctx *ctx)
887 int fd, fd_cap, ifindex, ttl;
888 struct ring dummy_ring;
889 struct sockaddr_storage ss, sd;
890 uint8_t *pkt_snd, *pkt_rcv;
892 fd = get_remote_fd(ctx, &ss, &sd);
893 fd_cap = pf_socket();
895 inject_filter(ctx, fd_cap);
897 ifindex = device_ifindex(ctx->dev);
898 bind_ring_generic(fd_cap, &dummy_ring, ifindex, false);
900 if (ctx->totlen < af_ops[ctx->proto].min_len_tcp) {
901 ctx->totlen = af_ops[ctx->proto].min_len_tcp;
902 if (ctx->payload)
903 ctx->totlen += strlen(ctx->payload);
906 ctx->rcvlen = device_mtu(ctx->dev) - sizeof(struct ethhdr);
907 if (ctx->totlen >= ctx->rcvlen)
908 panic("Packet len exceeds device MTU!\n");
910 pkt_snd = xmalloc(ctx->totlen);
911 pkt_rcv = xmalloc(ctx->rcvlen);
913 show_trace_info(ctx, &ss, &sd);
915 for (ttl = ctx->init_ttl; ttl <= ctx->max_ttl && sigint == 0; ++ttl)
916 __process_ttl(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv,
917 &ss, &sd);
919 xfree(pkt_snd);
920 xfree(pkt_rcv);
922 close(fd_cap);
923 close(fd);
925 return 0;
928 int main(int argc, char **argv)
930 int c, opt_index, ret;
931 struct ctx ctx;
933 setfsuid(getuid());
934 setfsgid(getgid());
936 srand(time(NULL));
938 memset(&ctx, 0, sizeof(ctx));
939 ctx.init_ttl = 1;
940 ctx.max_ttl = 30;
941 ctx.queries = 2;
942 ctx.timeout = 2;
943 ctx.proto = IPPROTO_IP;
944 ctx.payload = NULL;
945 ctx.dev = xstrdup("eth0");
946 ctx.port = xstrdup("80");
947 ctx.bind_addr = NULL;
949 while ((c = getopt_long(argc, argv, short_options, long_options,
950 &opt_index)) != EOF) {
951 switch (c) {
952 case 'h':
953 help();
954 break;
955 case 'v':
956 version();
957 break;
958 case 'u':
959 update_geoip();
960 die();
961 break;
962 case 'H':
963 ctx.host = xstrdup(optarg);
964 break;
965 case 'p':
966 if (ctx.port)
967 xfree(ctx.port);
968 ctx.port = xstrdup(optarg);
969 break;
970 case 'n':
971 ctx.dns_resolv = 0;
972 break;
973 case '4':
974 ctx.proto = IPPROTO_IP;
975 break;
976 case '6':
977 ctx.proto = IPPROTO_IPV6;
978 break;
979 case 'Z':
980 ctx.show = 1;
981 break;
982 case 'N':
983 ctx.dns_resolv = 1;
984 break;
985 case 'f':
986 ctx.init_ttl = atoi(optarg);
987 if (ctx.init_ttl <= 0)
988 help();
989 break;
990 case 'm':
991 ctx.max_ttl = atoi(optarg);
992 if (ctx.max_ttl <= 0)
993 help();
994 break;
995 case 'b':
996 ctx.bind_addr = xstrdup(optarg);
997 break;
998 case 'i':
999 case 'd':
1000 free(ctx.dev);
1001 ctx.dev = xstrdup(optarg);
1002 break;
1003 case 'q':
1004 ctx.queries = atoi(optarg);
1005 if (ctx.queries <= 0)
1006 help();
1007 break;
1008 case 'x':
1009 ctx.timeout = atoi(optarg);
1010 if (ctx.timeout <= 0)
1011 help();
1012 break;
1013 case 'L':
1014 ctx.latitude = 1;
1015 break;
1016 case 'S':
1017 ctx.syn = 1;
1018 break;
1019 case 'A':
1020 ctx.ack = 1;
1021 break;
1022 case 'F':
1023 ctx.fin = 1;
1024 break;
1025 case 'U':
1026 ctx.urg = 1;
1027 break;
1028 case 'P':
1029 ctx.psh = 1;
1030 break;
1031 case 'R':
1032 ctx.rst = 1;
1033 break;
1034 case 'E':
1035 ctx.syn = 1;
1036 ctx.ecn = 1;
1037 break;
1038 case 't':
1039 ctx.tos = atoi(optarg);
1040 if (ctx.tos < 0)
1041 help();
1042 break;
1043 case 'G':
1044 ctx.nofrag = 1;
1045 break;
1046 case 'X':
1047 ctx.payload = xstrdup(optarg);
1048 break;
1049 case 'l':
1050 ctx.totlen = strtoul(optarg, NULL, 10);
1051 if (ctx.totlen == 0)
1052 help();
1053 break;
1054 case '?':
1055 switch (optopt) {
1056 case 'H':
1057 case 'p':
1058 case 'f':
1059 case 'm':
1060 case 'i':
1061 case 'd':
1062 case 'q':
1063 case 'x':
1064 case 'X':
1065 case 't':
1066 case 'l':
1067 panic("Option -%c requires an argument!\n",
1068 optopt);
1069 default:
1070 if (isprint(optopt))
1071 printf("Unknown option character `0x%X\'!\n", optopt);
1072 die();
1074 default:
1075 break;
1079 if (argc < 3 || !ctx.host || !ctx.port || ctx.init_ttl > ctx.max_ttl ||
1080 ctx.init_ttl > MAXTTL || ctx.max_ttl > MAXTTL)
1081 help();
1083 if (!device_up_and_running(ctx.dev))
1084 panic("Networking device not up and running!\n");
1085 if (device_mtu(ctx.dev) <= ctx.totlen)
1086 panic("Packet larger than device MTU!\n");
1088 register_signal(SIGHUP, signal_handler);
1089 register_signal(SIGINT, signal_handler);
1090 register_signal(SIGQUIT, signal_handler);
1091 register_signal(SIGTERM, signal_handler);
1093 tprintf_init();
1094 init_geoip(1);
1096 ret = main_trace(&ctx);
1098 destroy_geoip();
1099 tprintf_cleanup();
1101 free(ctx.dev);
1102 free(ctx.host);
1103 free(ctx.port);
1104 free(ctx.bind_addr);
1105 free(ctx.payload);
1107 return ret;