mausezahn: Don't use ternary operator to decide which function to call
[netsniff-ng.git] / astraceroute.c
blob2f3449efe7d694215de365c70fe9124840c74722
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 "ioops.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 int init_ttl, max_ttl, dns_resolv, queries, timeout;
54 int syn, ack, ecn, fin, psh, rst, urg, tos, nofrag, proto, show;
55 int sd_len, dport, latitude;
58 struct proto_ops {
59 int (*assembler)(uint8_t *packet, size_t len, int ttl, int proto,
60 const struct ctx *ctx, const struct sockaddr *dst,
61 const struct sockaddr *src);
62 const struct sock_filter *filter;
63 unsigned int flen;
64 size_t min_len_tcp, min_len_icmp;
65 int (*check)(uint8_t *packet, size_t len, int ttl, int id,
66 const struct sockaddr *src);
67 void (*handler)(uint8_t *packet, size_t len, int dns_resolv,
68 int latitude);
71 static sig_atomic_t sigint = 0;
73 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
74 const struct ctx *ctx, const struct sockaddr *dst,
75 const struct sockaddr *src);
76 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
77 const struct ctx *ctx, const struct sockaddr *dst,
78 const struct sockaddr *src);
79 static int check_ipv4(uint8_t *packet, size_t len, int ttl, int id,
80 const struct sockaddr *ss);
81 static void handle_ipv4(uint8_t *packet, size_t len, int dns_resolv,
82 int latitude);
83 static int check_ipv6(uint8_t *packet, size_t len, int ttl, int id,
84 const struct sockaddr *ss);
85 static void handle_ipv6(uint8_t *packet, size_t len, int dns_resolv,
86 int latitude);
88 static const char *short_options = "H:p:nNf:m:b:i:d:q:x:SAEFPURt:Gl:hv46X:ZuL";
89 static const struct option long_options[] = {
90 {"host", required_argument, NULL, 'H'},
91 {"port", required_argument, NULL, 'p'},
92 {"init-ttl", required_argument, NULL, 'f'},
93 {"max-ttl", required_argument, NULL, 'm'},
94 {"bind", required_argument, NULL, 'b'},
95 {"dev", required_argument, NULL, 'd'},
96 {"num-probes", required_argument, NULL, 'q'},
97 {"timeout", required_argument, NULL, 'x'},
98 {"tos", required_argument, NULL, 't'},
99 {"payload", required_argument, NULL, 'X'},
100 {"totlen", required_argument, NULL, 'l'},
101 {"numeric", no_argument, NULL, 'n'},
102 {"latitude", no_argument, NULL, 'L'},
103 {"update", no_argument, NULL, 'u'},
104 {"dns", no_argument, NULL, 'N'},
105 {"ipv4", no_argument, NULL, '4'},
106 {"ipv6", no_argument, NULL, '6'},
107 {"syn", no_argument, NULL, 'S'},
108 {"ack", no_argument, NULL, 'A'},
109 {"urg", no_argument, NULL, 'U'},
110 {"fin", no_argument, NULL, 'F'},
111 {"psh", no_argument, NULL, 'P'},
112 {"rst", no_argument, NULL, 'R'},
113 {"ecn-syn", no_argument, NULL, 'E'},
114 {"show-packet", no_argument, NULL, 'Z'},
115 {"nofrag", no_argument, NULL, 'G'},
116 {"version", no_argument, NULL, 'v'},
117 {"help", no_argument, NULL, 'h'},
118 {NULL, 0, NULL, 0}
121 static const struct sock_filter ipv4_icmp_type_11[] = {
122 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
123 { 0x15, 0, 8, 0x00000800 }, /* jneq #0x800, drop */
124 { 0x30, 0, 0, 0x00000017 }, /* ldb [23] */
125 { 0x15, 0, 6, 0x00000001 }, /* jneq #0x1, drop */
126 { 0x28, 0, 0, 0x00000014 }, /* ldh [20] */
127 { 0x45, 4, 0, 0x00001fff }, /* jset #0x1fff, drop */
128 { 0xb1, 0, 0, 0x0000000e }, /* ldxb 4*([14]&0xf) */
129 { 0x50, 0, 0, 0x0000000e }, /* ldb [x + 14] */
130 { 0x15, 0, 1, 0x0000000b }, /* jneq #0xb, drop */
131 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
132 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
135 static const struct sock_filter ipv6_icmp6_type_3[] = {
136 { 0x28, 0, 0, 0x0000000c }, /* ldh [12] */
137 { 0x15, 0, 5, 0x000086dd }, /* jneq #0x86dd, drop */
138 { 0x30, 0, 0, 0x00000014 }, /* ldb [20] */
139 { 0x15, 0, 3, 0x0000003a }, /* jneq #0x3a, drop */
140 { 0x30, 0, 0, 0x00000036 }, /* ldb [54] */
141 { 0x15, 0, 1, 0x00000003 }, /* jneq #0x3, drop */
142 { 0x06, 0, 0, 0xffffffff }, /* ret #-1 */
143 { 0x06, 0, 0, 0x00000000 }, /* drop: ret #0 */
146 static const struct proto_ops af_ops[] = {
147 [IPPROTO_IP] = {
148 .assembler = assemble_ipv4,
149 .handler = handle_ipv4,
150 .check = check_ipv4,
151 .filter = ipv4_icmp_type_11,
152 .flen = array_size(ipv4_icmp_type_11),
153 .min_len_tcp = sizeof(struct iphdr) + sizeof(struct tcphdr),
154 .min_len_icmp = sizeof(struct iphdr) + sizeof(struct icmphdr),
156 [IPPROTO_IPV6] = {
157 .assembler = assemble_ipv6,
158 .handler = handle_ipv6,
159 .check = check_ipv6,
160 .filter = ipv6_icmp6_type_3,
161 .flen = array_size(ipv6_icmp6_type_3),
162 .min_len_tcp = sizeof(struct ip6_hdr) + sizeof(struct tcphdr),
163 .min_len_icmp = sizeof(struct ip6_hdr) + sizeof(struct icmp6hdr),
167 static void signal_handler(int number)
169 switch (number) {
170 case SIGINT:
171 case SIGQUIT:
172 case SIGTERM:
173 sigint = 1;
174 default:
175 break;
179 static void __noreturn help(void)
181 printf("\nastraceroute %s, autonomous system trace route utility\n", VERSION_STRING);
182 puts("http://www.netsniff-ng.org\n\n"
183 "Usage: astraceroute [options]\n"
184 "Options:\n"
185 " -H|--host <host> Host/IPv4/IPv6 to lookup AS route to\n"
186 " -p|--port <port> Hosts port to lookup AS route to\n"
187 " -i|-d|--dev <device> Networking device, e.g. eth0\n"
188 " -b|--bind <IP> IP address to bind to, Must specify -6 for an IPv6 address\n"
189 " -f|--init-ttl <ttl> Set initial TTL\n"
190 " -m|--max-ttl <ttl> Set maximum TTL (def: 30)\n"
191 " -q|--num-probes <num> Number of max probes for each hop (def: 2)\n"
192 " -x|--timeout <sec> Probe response timeout in sec (def: 3)\n"
193 " -X|--payload <string> Specify a payload string to test DPIs\n"
194 " -l|--totlen <len> Specify total packet len\n"
195 " -4|--ipv4 Use IPv4-only requests\n"
196 " -6|--ipv6 Use IPv6-only requests\n"
197 " -n|--numeric Do not do reverse DNS lookup for hops\n"
198 " -u|--update Update GeoIP databases\n"
199 " -L|--latitude Show latitude and longitude\n"
200 " -N|--dns Do a reverse DNS lookup for hops\n"
201 " -S|--syn Set TCP SYN flag\n"
202 " -A|--ack Set TCP ACK flag\n"
203 " -F|--fin Set TCP FIN flag\n"
204 " -P|--psh Set TCP PSH flag\n"
205 " -U|--urg Set TCP URG flag\n"
206 " -R|--rst Set TCP RST flag\n"
207 " -E|--ecn-syn Send ECN SYN packets (RFC3168)\n"
208 " -t|--tos <tos> Set the IP TOS field\n"
209 " -G|--nofrag Set do not fragment bit\n"
210 " -Z|--show-packet Show returned packet on each hop\n"
211 " -v|--version Print version and exit\n"
212 " -h|--help Print this help and exit\n\n"
213 "Examples:\n"
214 " IPv4 trace of AS with TCP SYN probe (this will most-likely pass):\n"
215 " astraceroute -i eth0 -N -S -H netsniff-ng.org\n"
216 " IPv4 trace of AS with TCP ECN SYN probe:\n"
217 " astraceroute -i eth0 -N -E -H netsniff-ng.org\n"
218 " IPv4 trace of AS with TCP FIN probe:\n"
219 " astraceroute -i eth0 -N -F -H netsniff-ng.org\n"
220 " IPv4 trace of AS with Xmas probe:\n"
221 " astraceroute -i eth0 -N -FPU -H netsniff-ng.org\n"
222 " IPv4 trace of AS with Null probe with ASCII payload:\n"
223 " astraceroute -i eth0 -N -H netsniff-ng.org -X \"censor-me\" -Z\n"
224 " IPv6 trace of AS up to www.6bone.net:\n"
225 " astraceroute -6 -i eth0 -S -E -N -H www.6bone.net\n\n"
226 "Note:\n"
227 " If the TCP probe did not give any results, then astraceroute will\n"
228 " automatically probe for classic ICMP packets! To gather more\n"
229 " information about astraceroute's fetched AS numbers, see e.g.\n"
230 " http://bgp.he.net/AS<number>!\n\n"
231 "Please report bugs to <bugs@netsniff-ng.org>\n"
232 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
233 "Swiss federal institute of technology (ETH Zurich)\n"
234 "License: GNU GPL version 2.0\n"
235 "This is free software: you are free to change and redistribute it.\n"
236 "There is NO WARRANTY, to the extent permitted by law.\n");
237 die();
240 static void __noreturn version(void)
242 printf("\nastraceroute %s, Git id: %s\n", VERSION_LONG, GITVERSION);
243 puts("autonomous system trace route utility\n"
244 "http://www.netsniff-ng.org\n\n"
245 "Please report bugs to <bugs@netsniff-ng.org>\n"
246 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
247 "Swiss federal institute of technology (ETH Zurich)\n"
248 "License: GNU GPL version 2.0\n"
249 "This is free software: you are free to change and redistribute it.\n"
250 "There is NO WARRANTY, to the extent permitted by law.\n");
251 die();
254 static void __assemble_data(uint8_t *packet, size_t len, const char *payload)
256 size_t i;
258 if (payload == NULL) {
259 for (i = 0; i < len; ++i)
260 packet[i] = (uint8_t) rand();
261 } else {
262 size_t lmin = min(len, strlen(payload));
264 for (i = 0; i < lmin; ++i)
265 packet[i] = (uint8_t) payload[i];
266 for (i = lmin; i < len; ++i)
267 packet[i] = (uint8_t) rand();
271 static void __assemble_icmp4(uint8_t *packet, size_t len)
273 struct icmphdr *icmph = (struct icmphdr *) packet;
275 bug_on(len < sizeof(struct icmphdr));
277 icmph->type = ICMP_ECHO;
278 icmph->code = 0;
279 icmph->checksum = 0;
282 static void __assemble_icmp6(uint8_t *packet, size_t len)
284 struct icmp6hdr *icmp6h = (struct icmp6hdr *) packet;
286 bug_on(len < sizeof(struct icmp6hdr));
288 icmp6h->icmp6_type = ICMPV6_ECHO_REQUEST;
289 icmp6h->icmp6_code = 0;
290 icmp6h->icmp6_cksum = 0;
293 static void __assemble_tcp(uint8_t *packet, size_t len, int syn, int ack,
294 int urg, int fin, int rst, int psh, int ecn,
295 int dport)
297 struct tcphdr *tcph = (struct tcphdr *) packet;
299 bug_on(len < sizeof(struct tcphdr));
301 tcph->source = htons((uint16_t) rand());
302 tcph->dest = htons((uint16_t) dport);
304 tcph->seq = htonl(rand());
305 tcph->ack_seq = (!!ack ? htonl(rand()) : 0);
307 tcph->doff = 5;
309 tcph->syn = !!syn;
310 tcph->ack = !!ack;
311 tcph->urg = !!urg;
312 tcph->fin = !!fin;
313 tcph->rst = !!rst;
314 tcph->psh = !!psh;
315 tcph->ece = !!ecn;
316 tcph->cwr = !!ecn;
318 tcph->window = htons((uint16_t) (100 + (rand() % 65435)));
319 tcph->urg_ptr = (!!urg ? htons((uint16_t) rand()) : 0);
320 tcph->check = 0;
323 static int assemble_ipv4(uint8_t *packet, size_t len, int ttl, int proto,
324 const struct ctx *ctx, const struct sockaddr *dst,
325 const struct sockaddr *src)
327 uint8_t *data;
328 size_t data_len, off_next = 0;
329 struct iphdr *iph = (struct iphdr *) packet;
331 bug_on(!src || !dst);
332 bug_on(src->sa_family != PF_INET || dst->sa_family != PF_INET);
333 bug_on(len < sizeof(*iph) + min(sizeof(struct tcphdr),
334 sizeof(struct icmphdr)));
336 iph->ihl = 5;
337 iph->version = 4;
338 iph->tos = (uint8_t) ctx->tos;
340 iph->tot_len = htons((uint16_t) len);
341 iph->id = htons((uint16_t) rand());
343 iph->frag_off = ctx->nofrag ? IP_DF : 0;
344 iph->ttl = (uint8_t) ttl;
346 iph->saddr = ((const struct sockaddr_in *) src)->sin_addr.s_addr;
347 iph->daddr = ((const struct sockaddr_in *) dst)->sin_addr.s_addr;
349 iph->protocol = (uint8_t) proto;
351 data = packet + sizeof(*iph);
352 data_len = len - sizeof(*iph);
354 switch (proto) {
355 case IPPROTO_TCP:
356 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
357 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
358 off_next = sizeof(struct tcphdr);
359 break;
360 case IPPROTO_ICMP:
361 __assemble_icmp4(data, data_len);
362 off_next = sizeof(struct icmphdr);
363 break;
364 default:
365 bug();
368 data = packet + sizeof(*iph) + off_next;
369 data_len = len - sizeof(*iph) - off_next;
371 __assemble_data(data, data_len, ctx->payload);
373 iph->check = csum((unsigned short *) packet, ntohs(iph->tot_len) >> 1);
375 return ntohs(iph->id);
378 static int assemble_ipv6(uint8_t *packet, size_t len, int ttl, int proto,
379 const struct ctx *ctx, const struct sockaddr *dst,
380 const struct sockaddr *src)
382 uint8_t *data;
383 size_t data_len, off_next = 0;
384 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
386 bug_on(!src || !dst);
387 bug_on(src->sa_family != PF_INET6 || dst->sa_family != PF_INET6);
388 bug_on(len < sizeof(*ip6h) + min(sizeof(struct tcphdr),
389 sizeof(struct icmp6hdr)));
391 ip6h->ip6_flow = htonl(rand() & 0x000fffff);
392 ip6h->ip6_vfc = 0x60;
394 ip6h->ip6_plen = htons((uint16_t) len - sizeof(*ip6h));
395 ip6h->ip6_nxt = (uint8_t) proto;
396 ip6h->ip6_hlim = (uint8_t) ttl;
398 memcpy(&ip6h->ip6_src, &(((const struct sockaddr_in6 *)
399 src)->sin6_addr), sizeof(ip6h->ip6_src));
400 memcpy(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
401 dst)->sin6_addr), sizeof(ip6h->ip6_dst));
403 data = packet + sizeof(*ip6h);
404 data_len = len - sizeof(*ip6h);
406 switch (proto) {
407 case IPPROTO_TCP:
408 __assemble_tcp(data, data_len, ctx->syn, ctx->ack, ctx->urg,
409 ctx->fin, ctx->rst, ctx->psh, ctx->ecn, ctx->dport);
410 off_next = sizeof(struct tcphdr);
411 break;
412 case IPPROTO_ICMP:
413 case IPPROTO_ICMPV6:
414 __assemble_icmp6(data, data_len);
415 off_next = sizeof(struct icmp6hdr);
416 break;
417 default:
418 bug();
421 data = packet + sizeof(*ip6h) + off_next;
422 data_len = len - sizeof(*ip6h) - off_next;
424 __assemble_data(data, data_len, ctx->payload);
426 return ntohl(ip6h->ip6_flow) & 0x000fffff;
429 static int check_ipv4(uint8_t *packet, size_t len, int ttl __maybe_unused,
430 int id, const struct sockaddr *ss)
432 struct iphdr *iph = (struct iphdr *) packet;
433 struct iphdr *iph_inner;
434 struct icmphdr *icmph;
436 if (iph->protocol != IPPROTO_ICMP)
437 return -EINVAL;
438 if (iph->daddr != ((const struct sockaddr_in *) ss)->sin_addr.s_addr)
439 return -EINVAL;
441 icmph = (struct icmphdr *) (packet + sizeof(struct iphdr));
442 if (icmph->type != ICMP_TIME_EXCEEDED)
443 return -EINVAL;
444 if (icmph->code != ICMP_EXC_TTL)
445 return -EINVAL;
447 iph_inner = (struct iphdr *) (packet + sizeof(struct iphdr) +
448 sizeof(struct icmphdr));
449 if (ntohs(iph_inner->id) != id)
450 return -EINVAL;
452 return len;
455 static void handle_ipv4(uint8_t *packet, size_t len __maybe_unused,
456 int dns_resolv, int latitude)
458 char hbuff[NI_MAXHOST];
459 struct iphdr *iph = (struct iphdr *) packet;
460 struct sockaddr_in sd;
461 struct hostent *hent;
462 const char *as, *country, *city;
464 memset(hbuff, 0, sizeof(hbuff));
465 memset(&sd, 0, sizeof(sd));
466 sd.sin_family = PF_INET;
467 sd.sin_addr.s_addr = iph->saddr;
469 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
470 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
472 as = geoip4_as_name(&sd);
473 country = geoip4_country_name(&sd);
474 city = geoip4_city_name(&sd);
476 if (dns_resolv) {
477 hent = gethostbyaddr(&sd.sin_addr, sizeof(sd.sin_addr), PF_INET);
478 if (hent)
479 printf(" %s (%s)", hent->h_name, hbuff);
480 else
481 printf(" %s", hbuff);
482 } else {
483 printf(" %s", hbuff);
485 if (as)
486 printf(" in %s", as);
487 if (country) {
488 printf(" in %s", country);
489 if (city)
490 printf(", %s", city);
492 if (latitude)
493 printf(" (%f/%f)", geoip4_latitude(&sd), geoip4_longitude(&sd));
496 static int check_ipv6(uint8_t *packet, size_t len, int ttl __maybe_unused,
497 int id, const struct sockaddr *ss)
499 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
500 struct ip6_hdr *ip6h_inner;
501 struct icmp6hdr *icmp6h;
503 if (ip6h->ip6_nxt != 0x3a)
504 return -EINVAL;
505 if (memcmp(&ip6h->ip6_dst, &(((const struct sockaddr_in6 *)
506 ss)->sin6_addr), sizeof(ip6h->ip6_dst)))
507 return -EINVAL;
509 icmp6h = (struct icmp6hdr *) (packet + sizeof(*ip6h));
510 if (icmp6h->icmp6_type != ICMPV6_TIME_EXCEED)
511 return -EINVAL;
512 if (icmp6h->icmp6_code != ICMPV6_EXC_HOPLIMIT)
513 return -EINVAL;
515 ip6h_inner = (struct ip6_hdr *) (packet + sizeof(*ip6h) + sizeof(*icmp6h));
516 if ((ntohl(ip6h_inner->ip6_flow) & 0x000fffff) != (uint32_t) id)
517 return -EINVAL;
519 return len;
522 static void handle_ipv6(uint8_t *packet, size_t len __maybe_unused,
523 int dns_resolv, int latitude)
525 char hbuff[NI_MAXHOST];
526 struct ip6_hdr *ip6h = (struct ip6_hdr *) packet;
527 struct sockaddr_in6 sd;
528 struct hostent *hent;
529 const char *as, *country, *city;
531 memset(hbuff, 0, sizeof(hbuff));
532 memset(&sd, 0, sizeof(sd));
533 sd.sin6_family = PF_INET6;
534 memcpy(&sd.sin6_addr, &ip6h->ip6_src, sizeof(ip6h->ip6_src));
536 getnameinfo((struct sockaddr *) &sd, sizeof(sd),
537 hbuff, sizeof(hbuff), NULL, 0, NI_NUMERICHOST);
539 as = geoip6_as_name(&sd);
540 country = geoip6_country_name(&sd);
541 city = geoip6_city_name(&sd);
543 if (dns_resolv) {
544 hent = gethostbyaddr(&sd.sin6_addr, sizeof(sd.sin6_addr), PF_INET6);
545 if (hent)
546 printf(" %s (%s)", hent->h_name, hbuff);
547 else
548 printf(" %s", hbuff);
549 } else {
550 printf(" %s", hbuff);
552 if (as)
553 printf(" in %s", as);
554 if (country) {
555 printf(" in %s", country);
556 if (city)
557 printf(", %s", city);
559 if (latitude)
560 printf(" (%f/%f)", geoip6_latitude(&sd), geoip6_longitude(&sd));
563 static void show_trace_info(struct ctx *ctx, const struct sockaddr_storage *ss,
564 const struct sockaddr_storage *sd)
566 char hbuffs[256], hbuffd[256];
568 memset(hbuffd, 0, sizeof(hbuffd));
569 getnameinfo((struct sockaddr *) sd, sizeof(*sd),
570 hbuffd, sizeof(hbuffd), NULL, 0, NI_NUMERICHOST);
572 memset(hbuffs, 0, sizeof(hbuffs));
573 getnameinfo((struct sockaddr *) ss, sizeof(*ss),
574 hbuffs, sizeof(hbuffs), NULL, 0, NI_NUMERICHOST);
576 printf("AS path IPv%d TCP trace from %s to %s:%s (%s) with len %zu "
577 "Bytes, %u max hops\n", ctx->proto == IPPROTO_IP ? 4 : 6,
578 hbuffs, hbuffd, ctx->port, ctx->host, ctx->totlen, ctx->max_ttl);
580 printf("Using flags SYN:%d,ACK:%d,ECN:%d,FIN:%d,PSH:%d,RST:%d,URG:%d\n",
581 ctx->syn, ctx->ack, ctx->ecn, ctx->fin, ctx->psh, ctx->rst, ctx->urg);
583 if (ctx->payload)
584 printf("With payload: \'%s\'\n", ctx->payload);
587 static int get_remote_fd(struct ctx *ctx, struct sockaddr_storage *ss,
588 struct sockaddr_storage *sd)
590 int fd = -1, ret, one = 1, af = AF_INET;
591 struct addrinfo hints, *ahead, *ai;
592 unsigned char bind_ip[sizeof(struct in6_addr)];
594 memset(&hints, 0, sizeof(hints));
595 hints.ai_family = PF_UNSPEC;
596 hints.ai_socktype = SOCK_STREAM;
597 hints.ai_protocol = IPPROTO_TCP;
598 hints.ai_flags = AI_NUMERICSERV;
600 ret = getaddrinfo(ctx->host, ctx->port, &hints, &ahead);
601 if (ret < 0)
602 panic("Cannot get address info!\n");
604 for (ai = ahead; ai != NULL && fd < 0; ai = ai->ai_next) {
605 if (!((ai->ai_family == PF_INET6 && ctx->proto == IPPROTO_IPV6) ||
606 (ai->ai_family == PF_INET && ctx->proto == IPPROTO_IP)))
607 continue;
609 fd = socket(ai->ai_family, SOCK_RAW, IPPROTO_RAW);
610 if (fd < 0)
611 continue;
613 memset(ss, 0, sizeof(*ss));
614 ret = device_address(ctx->dev, ai->ai_family, ss);
615 if (ret < 0 && !ctx->bind_addr)
616 panic("Cannot get own device address!\n");
618 if (ctx->bind_addr) {
619 if (ctx->proto == IPPROTO_IPV6)
620 af = AF_INET6;
622 if (inet_pton(af, ctx->bind_addr, &bind_ip) != 1)
623 panic("Address is invalid!\n");
625 if (af == AF_INET6) {
626 struct sockaddr_in6 *ss6 = (struct sockaddr_in6 *) ss;
627 memcpy(&ss6->sin6_addr.s6_addr, &bind_ip, sizeof(struct in6_addr));
628 } else {
629 struct sockaddr_in *ss4 = (struct sockaddr_in *) ss;
630 memcpy(&ss4->sin_addr.s_addr, &bind_ip, sizeof(struct in_addr));
634 ret = bind(fd, (struct sockaddr *) ss, sizeof(*ss));
635 if (ret < 0)
636 panic("Cannot bind socket!\n");
638 memset(sd, 0, sizeof(*sd));
639 memcpy(sd, ai->ai_addr, ai->ai_addrlen);
641 ctx->sd_len = ai->ai_addrlen;
642 ctx->dport = strtoul(ctx->port, NULL, 10);
644 ret = setsockopt(fd, ctx->proto, IP_HDRINCL, &one, sizeof(one));
645 if (ret < 0)
646 panic("Kernel does not support IP_HDRINCL!\n");
648 if (ai->ai_family == PF_INET6) {
649 struct sockaddr_in6 *sd6 = (struct sockaddr_in6 *) sd;
651 sd6->sin6_port = 0;
654 break;
657 freeaddrinfo(ahead);
659 if (fd < 0)
660 panic("Cannot create socket! Does remote "
661 "support IPv%d?!\n",
662 ctx->proto == IPPROTO_IP ? 4 : 6);
664 return fd;
667 static void inject_filter(struct ctx *ctx, int fd)
669 struct sock_fprog bpf_ops;
671 enable_kernel_bpf_jit_compiler();
673 memset(&bpf_ops, 0, sizeof(bpf_ops));
674 bpf_ops.filter = (struct sock_filter *) af_ops[ctx->proto].filter;
675 bpf_ops.len = af_ops[ctx->proto].flen;
677 bpf_attach_to_sock(fd, &bpf_ops);
680 static int __process_node(struct ctx *ctx, int fd, int fd_cap, int ttl,
681 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
682 const struct sockaddr_storage *ss,
683 const struct sockaddr_storage *sd, struct timeval *diff)
685 int pkt_id, ret, timeout;
686 struct pollfd pfd;
687 struct timeval start, end;
689 prepare_polling(fd_cap, &pfd);
691 memset(pkt_snd, 0, ctx->totlen);
692 pkt_id = af_ops[ctx->proto].assembler(pkt_snd, ctx->totlen, ttl,
693 inner_proto, ctx,
694 (const struct sockaddr *) sd,
695 (const struct sockaddr *) ss);
697 ret = sendto(fd, pkt_snd, ctx->totlen, 0, (struct sockaddr *) sd,
698 ctx->sd_len);
699 if (ret < 0)
700 panic("sendto failed: %s\n", strerror(errno));
702 bug_on(gettimeofday(&start, NULL));
704 timeout = (ctx->timeout > 0 ? ctx->timeout : 2) * 1000;
706 ret = poll(&pfd, 1, timeout);
707 if (ret > 0 && pfd.revents & POLLIN && sigint == 0) {
708 bug_on(gettimeofday(&end, NULL));
709 if (diff)
710 timersub(&end, &start, diff);
712 ret = recvfrom(fd_cap, pkt_rcv, ctx->rcvlen, 0, NULL, NULL);
713 if (ret < (int) (sizeof(struct ethhdr) + af_ops[ctx->proto].min_len_icmp))
714 return -EIO;
716 return af_ops[ctx->proto].check(pkt_rcv + sizeof(struct ethhdr),
717 ret - sizeof(struct ethhdr), ttl,
718 pkt_id, (const struct sockaddr *) ss);
719 } else {
720 return -EIO;
723 return 0;
726 static void timerdiv(const unsigned long divisor, const struct timeval *tv,
727 struct timeval *result)
729 uint64_t x = ((uint64_t) tv->tv_sec * 1000 * 1000 + tv->tv_usec) / divisor;
731 result->tv_sec = x / 1000 / 1000;
732 result->tv_usec = x % (1000 * 1000);
735 static int timevalcmp(const void *t1, const void *t2)
737 if (timercmp((struct timeval *) t1, (struct timeval *) t2, <))
738 return -1;
739 if (timercmp((struct timeval *) t1, (struct timeval *) t2, >))
740 return 1;
742 return 0;
745 static int __process_time(struct ctx *ctx, int fd, int fd_cap, int ttl,
746 int inner_proto, uint8_t *pkt_snd, uint8_t *pkt_rcv,
747 const struct sockaddr_storage *ss,
748 const struct sockaddr_storage *sd)
750 size_t i, j = 0;
751 int good = 0, ret = -EIO, idx, ret_good = -EIO;
752 struct timeval probes[9], *tmp, sum, res;
753 uint8_t *trash = xmalloc(ctx->rcvlen);
754 char *cwait[] = { "-", "\\", "|", "/" };
755 const char *proto_short[] = {
756 [IPPROTO_TCP] = "t",
757 [IPPROTO_ICMP] = "i",
758 [IPPROTO_ICMPV6] = "i",
761 memset(probes, 0, sizeof(probes));
762 for (i = 0; i < array_size(probes) && sigint == 0; ++i) {
763 ret = __process_node(ctx, fd, fd_cap, ttl, inner_proto,
764 pkt_snd, good == 0 ? pkt_rcv : trash,
765 ss, sd, &probes[i]);
766 if (ret > 0) {
767 if (good == 0)
768 ret_good = ret;
769 good++;
772 if (good == 0 && ctx->queries == (int) i)
773 break;
775 usleep(50000);
777 printf("\r%2d: %s", ttl, cwait[j++]);
778 fflush(stdout);
779 if (j >= array_size(cwait))
780 j = 0;
783 if (good == 0) {
784 xfree(trash);
785 return -EIO;
788 tmp = xmalloc(sizeof(struct timeval) * good);
789 for (i = j = 0; i < array_size(probes); ++i) {
790 if (probes[i].tv_sec == 0 && probes[i].tv_usec == 0)
791 continue;
792 tmp[j].tv_sec = probes[i].tv_sec;
793 tmp[j].tv_usec = probes[i].tv_usec;
794 j++;
797 qsort(tmp, j, sizeof(struct timeval), timevalcmp);
799 printf("\r%2d: %s[", ttl, proto_short[inner_proto]);
800 idx = j / 2;
801 switch (j % 2) {
802 case 0:
803 timeradd(&tmp[idx], &tmp[idx - 1], &sum);
804 timerdiv(2, &sum, &res);
805 if (res.tv_sec > 0)
806 printf("%lu sec ", res.tv_sec);
807 printf("%7lu us", res.tv_usec);
808 break;
809 case 1:
810 if (tmp[idx].tv_sec > 0)
811 printf("%lu sec ", tmp[idx].tv_sec);
812 printf("%7lu us", tmp[idx].tv_usec);
813 break;
815 printf("]");
817 xfree(tmp);
818 xfree(trash);
820 return ret_good;
823 static int __probe_remote(struct ctx *ctx, int fd, int fd_cap, int ttl,
824 uint8_t *pkt_snd, uint8_t *pkt_rcv,
825 const struct sockaddr_storage *ss,
826 const struct sockaddr_storage *sd,
827 int inner_proto)
829 int ret = -EIO, tries = ctx->queries;
831 while (tries-- > 0 && sigint == 0) {
832 ret = __process_time(ctx, fd, fd_cap, ttl, inner_proto,
833 pkt_snd, pkt_rcv, ss, sd);
834 if (ret < 0)
835 continue;
837 af_ops[ctx->proto].handler(pkt_rcv + sizeof(struct ethhdr),
838 ret - sizeof(struct ethhdr),
839 ctx->dns_resolv, ctx->latitude);
840 if (ctx->show) {
841 struct pkt_buff *pkt;
843 printf("\n");
844 pkt = pkt_alloc(pkt_rcv, ret);
845 hex_ascii(pkt);
846 tprintf_flush();
847 pkt_free(pkt);
850 break;
853 return ret;
856 static int __process_ttl(struct ctx *ctx, int fd, int fd_cap, int ttl,
857 uint8_t *pkt_snd, uint8_t *pkt_rcv,
858 const struct sockaddr_storage *ss,
859 const struct sockaddr_storage *sd)
861 int ret = -EIO;
862 size_t i;
863 const int inner_protos[] = {
864 IPPROTO_TCP,
865 IPPROTO_ICMP,
868 printf("%2d: ", ttl);
869 fflush(stdout);
871 for (i = 0; i < array_size(inner_protos) && sigint == 0; ++i) {
872 ret = __probe_remote(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv, ss, sd,
873 inner_protos[i]);
874 if (ret > 0)
875 break;
878 if (ret <= 0)
879 printf("\r%2d: ?[ no answer]", ttl);
880 if (ctx->show == 0)
881 printf("\n");
882 if (ctx->show && ret <= 0)
883 printf("\n\n");
885 fflush(stdout);
886 return 0;
889 static int main_trace(struct ctx *ctx)
891 int fd, fd_cap, ifindex, ttl;
892 struct ring dummy_ring;
893 struct sockaddr_storage ss, sd;
894 uint8_t *pkt_snd, *pkt_rcv;
896 fd = get_remote_fd(ctx, &ss, &sd);
897 fd_cap = pf_socket();
899 inject_filter(ctx, fd_cap);
901 ifindex = device_ifindex(ctx->dev);
902 bind_ring_generic(fd_cap, &dummy_ring, ifindex, false);
904 if (ctx->totlen < af_ops[ctx->proto].min_len_tcp) {
905 ctx->totlen = af_ops[ctx->proto].min_len_tcp;
906 if (ctx->payload)
907 ctx->totlen += strlen(ctx->payload);
910 ctx->rcvlen = device_mtu(ctx->dev) - sizeof(struct ethhdr);
911 if (ctx->totlen >= ctx->rcvlen)
912 panic("Packet len exceeds device MTU!\n");
914 pkt_snd = xmalloc(ctx->totlen);
915 pkt_rcv = xmalloc(ctx->rcvlen);
917 show_trace_info(ctx, &ss, &sd);
919 for (ttl = ctx->init_ttl; ttl <= ctx->max_ttl && sigint == 0; ++ttl)
920 __process_ttl(ctx, fd, fd_cap, ttl, pkt_snd, pkt_rcv,
921 &ss, &sd);
923 xfree(pkt_snd);
924 xfree(pkt_rcv);
926 close(fd_cap);
927 close(fd);
929 return 0;
932 int main(int argc, char **argv)
934 int c, opt_index, ret;
935 struct ctx ctx;
937 setfsuid(getuid());
938 setfsgid(getgid());
940 srand(time(NULL));
942 memset(&ctx, 0, sizeof(ctx));
943 ctx.init_ttl = 1;
944 ctx.max_ttl = 30;
945 ctx.queries = 2;
946 ctx.timeout = 2;
947 ctx.proto = IPPROTO_IP;
948 ctx.payload = NULL;
949 ctx.dev = xstrdup("eth0");
950 ctx.port = xstrdup("80");
951 ctx.bind_addr = NULL;
953 while ((c = getopt_long(argc, argv, short_options, long_options,
954 &opt_index)) != EOF) {
955 switch (c) {
956 case 'h':
957 help();
958 break;
959 case 'v':
960 version();
961 break;
962 case 'u':
963 update_geoip();
964 die();
965 break;
966 case 'H':
967 ctx.host = xstrdup(optarg);
968 break;
969 case 'p':
970 if (ctx.port)
971 xfree(ctx.port);
972 ctx.port = xstrdup(optarg);
973 break;
974 case 'n':
975 ctx.dns_resolv = 0;
976 break;
977 case '4':
978 ctx.proto = IPPROTO_IP;
979 break;
980 case '6':
981 ctx.proto = IPPROTO_IPV6;
982 break;
983 case 'Z':
984 ctx.show = 1;
985 break;
986 case 'N':
987 ctx.dns_resolv = 1;
988 break;
989 case 'f':
990 ctx.init_ttl = atoi(optarg);
991 if (ctx.init_ttl <= 0)
992 help();
993 break;
994 case 'm':
995 ctx.max_ttl = atoi(optarg);
996 if (ctx.max_ttl <= 0)
997 help();
998 break;
999 case 'b':
1000 ctx.bind_addr = xstrdup(optarg);
1001 break;
1002 case 'i':
1003 case 'd':
1004 free(ctx.dev);
1005 ctx.dev = xstrdup(optarg);
1006 break;
1007 case 'q':
1008 ctx.queries = atoi(optarg);
1009 if (ctx.queries <= 0)
1010 help();
1011 break;
1012 case 'x':
1013 ctx.timeout = atoi(optarg);
1014 if (ctx.timeout <= 0)
1015 help();
1016 break;
1017 case 'L':
1018 ctx.latitude = 1;
1019 break;
1020 case 'S':
1021 ctx.syn = 1;
1022 break;
1023 case 'A':
1024 ctx.ack = 1;
1025 break;
1026 case 'F':
1027 ctx.fin = 1;
1028 break;
1029 case 'U':
1030 ctx.urg = 1;
1031 break;
1032 case 'P':
1033 ctx.psh = 1;
1034 break;
1035 case 'R':
1036 ctx.rst = 1;
1037 break;
1038 case 'E':
1039 ctx.syn = 1;
1040 ctx.ecn = 1;
1041 break;
1042 case 't':
1043 ctx.tos = atoi(optarg);
1044 if (ctx.tos < 0)
1045 help();
1046 break;
1047 case 'G':
1048 ctx.nofrag = 1;
1049 break;
1050 case 'X':
1051 ctx.payload = xstrdup(optarg);
1052 break;
1053 case 'l':
1054 ctx.totlen = strtoul(optarg, NULL, 10);
1055 if (ctx.totlen == 0)
1056 help();
1057 break;
1058 case '?':
1059 switch (optopt) {
1060 case 'H':
1061 case 'p':
1062 case 'f':
1063 case 'm':
1064 case 'i':
1065 case 'd':
1066 case 'q':
1067 case 'x':
1068 case 'X':
1069 case 't':
1070 case 'l':
1071 panic("Option -%c requires an argument!\n",
1072 optopt);
1073 default:
1074 if (isprint(optopt))
1075 printf("Unknown option character `0x%X\'!\n", optopt);
1076 die();
1078 default:
1079 break;
1083 if (argc < 3 || !ctx.host || !ctx.port || ctx.init_ttl > ctx.max_ttl ||
1084 ctx.init_ttl > MAXTTL || ctx.max_ttl > MAXTTL)
1085 help();
1087 if (!device_up_and_running(ctx.dev))
1088 panic("Networking device not up and running!\n");
1089 if (device_mtu(ctx.dev) <= ctx.totlen)
1090 panic("Packet larger than device MTU!\n");
1092 register_signal(SIGHUP, signal_handler);
1093 register_signal(SIGINT, signal_handler);
1094 register_signal(SIGQUIT, signal_handler);
1095 register_signal(SIGTERM, signal_handler);
1097 tprintf_init();
1098 init_geoip(1);
1100 ret = main_trace(&ctx);
1102 destroy_geoip();
1103 tprintf_cleanup();
1105 free(ctx.dev);
1106 free(ctx.host);
1107 free(ctx.port);
1108 free(ctx.bind_addr);
1109 free(ctx.payload);
1111 return ret;