chiark / gitweb /
pathmtu/pathmtu.c (raw): Switchify the code.
[tripe] / pathmtu / pathmtu.c
1 /* -*-c-*-
2  *
3  * Report MTU on path to specified host
4  *
5  * (c) 2008 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Trivial IP Encryption (TrIPE).
11  *
12  * TrIPE is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your
15  * option) any later version.
16  *
17  * TrIPE is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
20  * for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with TrIPE.  If not, see <https://www.gnu.org/licenses/>.
24  */
25
26 /*----- Header files ------------------------------------------------------*/
27
28 #include "config.h"
29
30 #include <assert.h>
31 #include <errno.h>
32 #include <stddef.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <time.h>
37
38 #include <sys/types.h>
39 #include <sys/time.h>
40 #include <unistd.h>
41
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <netdb.h>
46
47 #include <netinet/in_systm.h>
48 #include <netinet/ip.h>
49 #include <netinet/ip_icmp.h>
50 #include <netinet/udp.h>
51
52 #include <net/if.h>
53 #include <ifaddrs.h>
54 #include <sys/ioctl.h>
55
56 #include <mLib/alloc.h>
57 #include <mLib/bits.h>
58 #include <mLib/dstr.h>
59 #include <mLib/hex.h>
60 #include <mLib/mdwopt.h>
61 #include <mLib/quis.h>
62 #include <mLib/report.h>
63 #include <mLib/tv.h>
64
65 /*----- Static variables --------------------------------------------------*/
66
67 static unsigned char buf[65536];
68
69 #define POLY 0x1002d
70
71 /*----- Utility functions -------------------------------------------------*/
72
73 /* Step a value according to a simple LFSR. */
74 #define STEP(q)                                                         \
75   do (q) = ((q) & 0x8000) ? ((q) << 1) ^ POLY : ((q) << 1); while (0)
76
77 /* Fill buffer with a constant but pseudorandom string.  Uses a simple
78  * LFSR.
79  */
80 static void fillbuffer(unsigned char *p, size_t sz)
81 {
82   unsigned int y = 0xbc20;
83   const unsigned char *l = p + sz;
84   int i;
85
86   while (p < l) {
87     *p++ = y & 0xff;
88     for (i = 0; i < 8; i++) STEP(y);
89   }
90 }
91
92 /* Convert a string to floating point. */
93 static double s2f(const char *s, const char *what)
94 {
95   double f;
96   char *q;
97
98   errno = 0;
99   f = strtod(s, &q);
100   if (errno || *q) die(EXIT_FAILURE, "bad %s", what);
101   return (f);
102 }
103
104 /* Convert a floating-point value into a struct timeval. */
105 static void f2tv(struct timeval *tv, double t)
106   { tv->tv_sec = t; tv->tv_usec = (t - tv->tv_sec)*MILLION; }
107
108 union addr {
109   struct sockaddr sa;
110   struct sockaddr_in sin;
111   struct sockaddr_in6 sin6;
112 };
113
114 /* Check whether an address family is even slightly supported. */
115 static int addrfamok(int af)
116 {
117   switch (af) {
118     case AF_INET: case AF_INET6: return (1);
119     default: return (0);
120   }
121 }
122
123 /* Return the size of a socket address. */
124 static size_t addrsz(const union addr *a)
125 {
126   switch (a->sa.sa_family) {
127     case AF_INET: return (sizeof(a->sin));
128     case AF_INET6: return (sizeof(a->sin6));
129     default: abort();
130   }
131 }
132
133 /* Compare two addresses.  Maybe compare the port numbers too. */
134 #define AEF_PORT 1u
135 static int addreq(const union addr *a, const union addr *b, unsigned f)
136 {
137   switch (a->sa.sa_family) {
138     case AF_INET:
139       return (a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr &&
140               (!(f&AEF_PORT) || a->sin.sin_port == b->sin.sin_port));
141     case AF_INET6:
142       return (!memcmp(a->sin6.sin6_addr.s6_addr,
143                       b->sin6.sin6_addr.s6_addr, 16) &&
144               (!(f&AEF_PORT) || a->sin6.sin6_port == b->sin6.sin6_port));
145     default:
146       abort();
147   }
148 }
149
150 /*----- Main algorithm skeleton -------------------------------------------*/
151
152 struct param {
153   unsigned f;                           /* Various flags */
154 #define F_VERBOSE 1u                    /*   Give a running commentary */
155   double retx;                          /* Initial retransmit interval */
156   double regr;                          /* Retransmit growth factor */
157   double timeout;                       /* Retransmission timeout */
158   int seqoff;                           /* Offset to write sequence number */
159   const struct probe_ops *pops;         /* Probe algorithm description */
160   union addr a;                         /* Destination address */
161 };
162
163 struct probestate {
164   const struct param *pp;
165   unsigned q;
166 };
167
168 struct probe_ops {
169   const char *name;
170   const struct probe_ops *next;
171   size_t statesz;
172   int (*setup)(void *, int, const struct param *);
173   void (*finish)(void *);
174   void (*selprep)(void *, int *, fd_set *);
175   int (*xmit)(void *, int);
176   int (*selproc)(void *, fd_set *, struct probestate *);
177 };
178
179 #define OPS_CHAIN 0
180
181 enum {
182   RC_FAIL = -99,
183   RC_OK = 0,
184   RC_LOWER = -1,
185   RC_HIGHER = -2,
186   RC_NOREPLY = -3
187   /* or a positive MTU upper-bound */
188 };
189
190 /* Add a file descriptor FD to the set `fd_in', updating `*maxfd'. */
191 #define ADDFD(fd) \
192   do { FD_SET(fd, fd_in); if (*maxfd < fd) *maxfd = fd; } while (0)
193
194 /* Check whether a buffer contains a packet from our current probe. */
195 static int mypacketp(struct probestate *ps,
196                      const unsigned char *p, size_t sz)
197 {
198   const struct param *pp = ps->pp;
199
200   return (sz >= pp->seqoff + 2 && LOAD16(p + pp->seqoff) == ps->q);
201 }
202
203 /* See whether MTU is an acceptable MTU value.  Return an appropriate
204  * RC_... code or a new suggested MTU.
205  */
206 static int probe(struct probestate *ps, void *st, int mtu)
207 {
208   const struct param *pp = ps->pp;
209   fd_set fd_in;
210   struct timeval tv, now, when, done;
211   double timer = pp->retx;
212   int rc, maxfd;
213
214   /* Set up the first retransmit and give-up timers. */
215   gettimeofday(&now, 0);
216   f2tv(&tv, pp->timeout); TV_ADD(&done, &now, &tv);
217   f2tv(&tv, timer); TV_ADD(&when, &now, &tv);
218   if (TV_CMP(&when, >, &done)) when = done;
219
220   /* Send the initial probe. */
221   if (pp->f & F_VERBOSE)
222     moan("sending probe of size %d (seq = %04x)", mtu, ps->q);
223   STEP(ps->q);
224   STORE16(buf + pp->seqoff, ps->q);
225   if ((rc = pp->pops->xmit(st, mtu)) != RC_OK) return (rc);
226
227   for (;;) {
228
229     /* Wait for something interesting to happen. */
230     maxfd = 0; FD_ZERO(&fd_in);
231     pp->pops->selprep(st, &maxfd, &fd_in);
232     TV_SUB(&tv, &when, &now);
233     if (select(maxfd + 1, &fd_in, 0, 0, &tv) < 0) return (RC_FAIL);
234     gettimeofday(&now, 0);
235
236     /* See whether the probe method has any answers for us. */
237     if ((rc = pp->pops->selproc(st, &fd_in, ps)) != RC_OK) return (rc);
238
239     /* If we've waited too long, give up.  If we should retransmit, do
240      * that.
241      */
242     if (TV_CMP(&now, >, &done))
243       return (RC_NOREPLY);
244     else if (TV_CMP(&now, >, &when)) {
245       if (pp->f & F_VERBOSE) moan("re-sending probe of size %d", mtu);
246       if ((rc = pp->pops->xmit(st, mtu)) != RC_OK) return (rc);
247       do {
248         timer *= pp->regr; f2tv(&tv, timer); TV_ADD(&when, &when, &tv);
249       } while (TV_CMP(&when, <, &now));
250       if (TV_CMP(&when, >, &done)) when = done;
251     }
252   }
253 }
254
255 /* Discover the path MTU to the destination address. */
256 static int pathmtu(const struct param *pp)
257 {
258   int sk;
259   int mtu, lo, hi;
260   int rc, droppy = -1;
261   void *st;
262   struct probestate ps;
263
264   /* Build and connect a UDP socket.  We'll need this to know the local port
265    * number to use if nothing else.  Set other stuff up.
266    */
267   if ((sk = socket(pp->a.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP)) < 0)
268     goto fail_0;
269   if (connect(sk, &pp->a.sa, addrsz(&pp->a))) goto fail_1;
270   st = xmalloc(pp->pops->statesz);
271   if ((mtu = pp->pops->setup(st, sk, pp)) < 0) goto fail_2;
272   ps.pp = pp; ps.q = rand() & 0xffff;
273   switch (pp->a.sa.sa_family) {
274     case AF_INET: lo = 576; break;
275     case AF_INET6: lo = 1280; break;
276     default: abort();
277   }
278   hi = mtu;
279   if (hi < lo) { errno = EMSGSIZE; return (-1); }
280
281   /* And now we do a thing which is sort of like a binary search, except that
282    * we also take explicit clues as establishing a new upper bound, and we
283    * try to hug that initially.
284    */
285   for (;;) {
286     assert(lo <= mtu && mtu <= hi);
287     if (pp->f & F_VERBOSE) moan("probe: %d <= %d <= %d", lo, mtu, hi);
288     rc = probe(&ps, st, mtu);
289     switch (rc) {
290
291       case RC_FAIL:
292         if (pp->f & F_VERBOSE) moan("probe failed");
293         goto fail_3;
294
295       case RC_NOREPLY:
296         /* If we've not seen a dropped packet before then we don't know what
297          * this means yet -- in particular, we don't know which bit of the
298          * network is swallowing packets.  Send a minimum-size probe.  If
299          * that doesn't come back then assume that the remote host is
300          * swallowing our packets.  If it does, then we assume that dropped
301          * packets are a result of ICMP fragmentation-needed reports being
302          * lost or suppressed.
303          */
304         if (pp->f & F_VERBOSE) moan("gave up: black hole detected");
305         if (droppy == -1) {
306           if (pp->f & F_VERBOSE) moan("sending minimum-size probe");
307           switch (probe(&ps, st, lo)) {
308             case RC_FAIL:
309               goto fail_3;
310             case RC_NOREPLY:
311               if (pp->f & F_VERBOSE) {
312                 moan("no reply from min-size probe: "
313                      "assume black hole at target");
314               }
315               droppy = 1;
316               break;
317             case RC_HIGHER:
318               if (pp->f & F_VERBOSE) {
319                 moan("reply from min-size probe OK: "
320                      "assume black hole in network");
321               }
322               droppy = 0;
323               break;
324             default:
325               if (pp->f & F_VERBOSE)
326                 moan("unexpected return code from probe");
327               errno = ENOTCONN;
328               goto fail_3;
329           }
330         }
331
332         if (droppy) goto higher; else goto lower;
333
334       case RC_HIGHER:
335       higher:
336         if (droppy == -1) {
337           if (pp->f & F_VERBOSE)
338             moan("probe returned: remote host is not a black hole");
339           droppy = 0;
340         }
341         if (mtu == hi) {
342           if (pp->f & F_VERBOSE) moan("probe returned: found correct MTU");
343           goto done;
344         }
345         lo = mtu;
346
347         /* Now we must make a new guess, between lo and hi.  We know that lo
348          * is good; but we're not so sure about hi here.  We know that hi >
349          * lo, so this will find an approximate midpoint, greater than lo and
350          * no more than hi.
351          */
352         if (pp->f & F_VERBOSE) moan("probe returned: guessing higher");
353         mtu += (hi - lo + 1)/2;
354         break;
355
356       case RC_LOWER:
357       lower:
358         /* If this didn't work, and we're already at the bottom of our
359          * possible range, then something has gone horribly wrong.
360          */
361         assert(lo < mtu);
362         hi = mtu - 1;
363         if (lo == hi) {
364           if (pp->f & F_VERBOSE) moan("error returned: found correct MTU");
365           mtu = lo;
366           goto done;
367         }
368
369         /* We must make a new guess, between lo and hi.  We're probably
370          * fairly sure that lo will succeed, since either it's the minimum
371          * MTU or we've tested it already; but we're not quite sure about hi,
372          * so we want to aim high.
373          */
374         if (pp->f & F_VERBOSE) moan("error returned: guessing lower");
375         mtu -= (hi - lo + 1)/2;
376         break;
377
378       default:
379         if (pp->f & F_VERBOSE) moan("error returned with new MTU estimate");
380         mtu = hi = rc;
381         break;
382     }
383   }
384
385 done:
386   /* Clean up and return our result. */
387   pp->pops->finish(st);
388   xfree(st);
389   close(sk);
390   return (mtu);
391
392 fail_3:
393   pp->pops->finish(st);
394 fail_2:
395   xfree(st);
396 fail_1:
397   close(sk);
398 fail_0:
399   return (-1);
400 }
401
402 /*----- Doing it the hard way ---------------------------------------------*/
403
404 #if defined(linux) || defined(__OpenBSD__)
405 #define IPHDR_SANE
406 #endif
407
408 #ifdef IPHDR_SANE
409 #  define sane_htons htons
410 #  define sane_htonl htonl
411 #else
412 #  define sane_htons
413 #  define sane_htonl
414 #endif
415
416 static int rawicmp = -1, rawudp = -1, rawerr = 0;
417
418 #define IPCK_INIT 0xffff
419
420 /* Compute an IP checksum over some data.  This is a restartable interface:
421  * initialize A to `IPCK_INIT' for the first call.
422  */
423 static unsigned ipcksum(const void *buf, size_t n, unsigned a)
424 {
425   unsigned long aa = a ^ 0xffff;
426   const unsigned char *p = buf, *l = p + n;
427
428   while (p < l - 1) { aa += LOAD16_B(p); p += 2; }
429   if (p < l) { aa += (unsigned)(*p) << 8; }
430   do aa = (aa & 0xffff) + (aa >> 16); while (aa >= 0x10000);
431   return (aa == 0xffff ? aa : aa ^ 0xffff);
432 }
433
434 /* TCP/UDP pseudoheader structure. */
435 struct phdr {
436   struct in_addr ph_src, ph_dst;
437   uint8_t ph_z, ph_p;
438   uint16_t ph_len;
439 };
440
441 struct raw_state {
442   union addr me, a;
443   int sk, rawicmp, rawudp;
444   uint16_t srcport, dstport;
445   unsigned q;
446 };
447
448 static int raw_setup(void *stv, int sk, const struct param *pp)
449 {
450   struct raw_state *st = stv;
451   socklen_t sz;
452   int i, mtu = -1;
453   struct ifaddrs *ifa, *ifaa, *ifap;
454   struct ifreq ifr;
455
456   /* Check that the address is OK, and that we have the necessary raw
457    * sockets.
458    */
459   switch (pp->a.sa.sa_family) {
460     case AF_INET:
461       if (rawerr) { errno = rawerr; goto fail_0; }
462       st->rawicmp = rawicmp; st->rawudp = rawudp; st->sk = sk;
463       break;
464     default:
465       errno = EPFNOSUPPORT; goto fail_0;
466   }
467
468   /* Initialize the sequence number. */
469   st->q = rand() & 0xffff;
470
471   /* Snaffle the local and remote address and port number. */
472   st->a = pp->a;
473   sz = sizeof(st->me);
474   if (getsockname(sk, &st->me.sa, &sz))
475     goto fail_0;
476
477   /* An unfortunate bodge which will make sense in the future. */
478   switch (pp->a.sa.sa_family) {
479     case AF_INET:
480       st->srcport = st->me.sin.sin_port; st->me.sin.sin_port = 0;
481       st->dstport =  st->a.sin.sin_port;  st->a.sin.sin_port = 0;
482       break;
483     default:
484       abort();
485   }
486
487   /* There isn't a portable way to force the DF flag onto a packet through
488    * UDP, or even through raw IP, unless we write the entire IP header
489    * ourselves.  This is somewhat annoying, especially since we have an
490    * uphill struggle keeping track of which systems randomly expect which
491    * header fields to be presented in host byte order.  Oh, well.
492    */
493   i = 1;
494   if (setsockopt(rawudp, IPPROTO_IP, IP_HDRINCL, &i, sizeof(i))) goto fail_0;
495
496   /* Find an upper bound on the MTU.  Do two passes over the interface
497    * list.  If we can find matches for our local address then use the
498    * highest one of those; otherwise do a second pass and simply take the
499    * highest MTU of any network interface.
500    */
501   if (getifaddrs(&ifaa)) goto fail_0;
502   for (i = 0; i < 2; i++) {
503     for (ifap = 0, ifa = ifaa; ifa; ifa = ifa->ifa_next) {
504       if (!(ifa->ifa_flags & IFF_UP) || !ifa->ifa_addr ||
505           ifa->ifa_addr->sa_family != st->me.sa.sa_family ||
506           (i == 0 &&
507            !addreq((union addr *)ifa->ifa_addr, &st->me, 0)) ||
508           (i == 1 && ifap && strcmp(ifap->ifa_name, ifa->ifa_name) == 0) ||
509           strlen(ifa->ifa_name) >= sizeof(ifr.ifr_name))
510         continue;
511       ifap = ifa;
512       strcpy(ifr.ifr_name, ifa->ifa_name);
513       if (ioctl(sk, SIOCGIFMTU, &ifr)) goto fail_1;
514       if (mtu < ifr.ifr_mtu) mtu = ifr.ifr_mtu;
515     }
516     if (mtu > 0) break;
517   }
518   if (mtu < 0) { errno = ENOTCONN; goto fail_1; }
519   freeifaddrs(ifaa);
520
521   /* Done. */
522   return (mtu);
523
524 fail_1:
525   freeifaddrs(ifaa);
526 fail_0:
527   return (-1);
528 }
529
530 static void raw_finish(void *stv) { ; }
531
532 static void raw_selprep(void *stv, int *maxfd, fd_set *fd_in)
533   { struct raw_state *st = stv; ADDFD(st->sk); ADDFD(st->rawicmp); }
534
535 static int raw_xmit(void *stv, int mtu)
536 {
537   struct raw_state *st = stv;
538   unsigned char b[65536], *p;
539   struct ip *ip;
540   struct udphdr *udp;
541   struct phdr ph;
542   unsigned ck;
543
544   switch (st->a.sa.sa_family) {
545
546     case AF_INET:
547
548       /* Build the IP header. */
549       ip = (struct ip *)b;
550       ip->ip_v = 4;
551       ip->ip_hl = sizeof(*ip)/4;
552       ip->ip_tos = IPTOS_RELIABILITY;
553       ip->ip_len = sane_htons(mtu);
554       STEP(st->q); ip->ip_id = htons(st->q);
555       ip->ip_off = sane_htons(0 | IP_DF);
556       ip->ip_ttl = 64;
557       ip->ip_p = IPPROTO_UDP;
558       ip->ip_sum = 0;
559       ip->ip_src = st->me.sin.sin_addr;
560       ip->ip_dst = st->a.sin.sin_addr;
561
562       /* Build a UDP packet in the output buffer. */
563       udp = (struct udphdr *)(ip + 1);
564       udp->uh_sport = st->srcport;
565       udp->uh_dport = st->dstport;
566       udp->uh_ulen = htons(mtu - sizeof(*ip));
567       udp->uh_sum = 0;
568
569       /* Copy the payload. */
570       p = (unsigned char *)(udp + 1);
571       memcpy(p, buf, mtu - (p - b));
572
573       /* Calculate the UDP checksum. */
574       ph.ph_src = ip->ip_src;
575       ph.ph_dst = ip->ip_dst;
576       ph.ph_z = 0;
577       ph.ph_p = IPPROTO_UDP;
578       ph.ph_len = udp->uh_ulen;
579       ck = IPCK_INIT;
580       ck = ipcksum(&ph, sizeof(ph), ck);
581       ck = ipcksum(udp, mtu - sizeof(*ip), ck);
582       udp->uh_sum = htons(ck);
583
584       break;
585
586     default:
587       abort();
588   }
589
590   /* Send the whole thing off.  If we're too big for the interface then we
591    * might need to trim immediately.
592    */
593   if (sendto(st->rawudp, b, mtu, 0, &st->a.sa, addrsz(&st->a)) < 0) {
594     if (errno == EMSGSIZE) return (RC_LOWER);
595     else goto fail_0;
596   }
597
598   /* Done. */
599   return (RC_OK);
600
601 fail_0:
602   return (RC_FAIL);
603 }
604
605 static int raw_selproc(void *stv, fd_set *fd_in, struct probestate *ps)
606 {
607   struct raw_state *st = stv;
608   unsigned char b[65536];
609   struct ip *ip;
610   struct icmp *icmp;
611   struct udphdr *udp;
612   const unsigned char *payload;
613   ssize_t n;
614
615   /* An ICMP packet: see what's inside. */
616   if (FD_ISSET(st->rawicmp, fd_in)) {
617     if ((n = read(st->rawicmp, b, sizeof(b))) < 0) goto fail_0;
618
619     switch (st->me.sa.sa_family) {
620
621       case AF_INET:
622
623         ip = (struct ip *)b;
624         if (n < sizeof(*ip) || n < sizeof(4*ip->ip_hl) ||
625             ip->ip_v != 4 || ip->ip_p != IPPROTO_ICMP)
626           goto skip_icmp;
627         n -= sizeof(4*ip->ip_hl);
628
629         icmp = (struct icmp *)(b + 4*ip->ip_hl);
630         if (n < sizeof(*icmp) || icmp->icmp_type != ICMP_UNREACH)
631           goto skip_icmp;
632         n -= offsetof(struct icmp, icmp_ip);
633
634         ip = &icmp->icmp_ip;
635         if (n < sizeof(*ip) ||
636             ip->ip_p != IPPROTO_UDP || ip->ip_hl != sizeof(*ip)/4 ||
637             ip->ip_id != htons(st->q) ||
638             ip->ip_src.s_addr != st->me.sin.sin_addr.s_addr ||
639             ip->ip_dst.s_addr != st->a.sin.sin_addr.s_addr)
640           goto skip_icmp;
641         n -= sizeof(*ip);
642
643         udp = (struct udphdr *)(ip + 1);
644         if (n < sizeof(*udp) || udp->uh_sport != st->srcport ||
645             udp->uh_dport != st->dstport)
646           goto skip_icmp;
647         n -= sizeof(*udp);
648
649         payload = (const unsigned char *)(udp + 1);
650         if (!mypacketp(ps, payload, n)) goto skip_icmp;
651
652         if (icmp->icmp_code == ICMP_UNREACH_PORT) return (RC_HIGHER);
653         else if (icmp->icmp_code != ICMP_UNREACH_NEEDFRAG) goto skip_icmp;
654         else if (icmp->icmp_nextmtu) return (htons(icmp->icmp_nextmtu));
655         else return (RC_LOWER);
656
657         break;
658
659       default:
660         abort();
661     }
662   }
663
664 skip_icmp:;
665
666   /* If we got a reply to the current probe then we're good.  If we got an
667    * error, or the packet's sequence number is wrong, then ignore it.
668    */
669   if (FD_ISSET(st->sk, fd_in)) {
670     if ((n = read(st->sk, b, sizeof(b))) < 0) return (RC_OK);
671     else if (mypacketp(ps, b, n)) return (RC_HIGHER);
672     else return (RC_OK);
673   }
674
675   return (RC_OK);
676
677 fail_0:
678   return (RC_FAIL);
679 }
680
681 static const struct probe_ops raw_ops = {
682   "raw", OPS_CHAIN, sizeof(struct raw_state),
683   raw_setup, raw_finish,
684   raw_selprep, raw_xmit, raw_selproc
685 };
686
687 #undef OPS_CHAIN
688 #define OPS_CHAIN &raw_ops
689
690 /*----- Doing the job on Linux --------------------------------------------*/
691
692 #if defined(linux)
693
694 #ifndef IP_MTU
695 #  define IP_MTU 14                     /* Blech! */
696 #endif
697
698 struct linux_state {
699   int sol, so_mtu_discover, so_mtu;
700   int sk;
701   size_t hdrlen;
702 };
703
704 static int linux_setup(void *stv, int sk, const struct param *pp)
705 {
706   struct linux_state *st = stv;
707   int i, mtu;
708   socklen_t sz;
709
710   /* Check that the address is OK. */
711   switch (pp->a.sa.sa_family) {
712     case AF_INET:
713       st->sol = IPPROTO_IP;
714       st->so_mtu_discover = IP_MTU_DISCOVER;
715       st->so_mtu = IP_MTU;
716       st->hdrlen = 28;
717       break;
718     case AF_INET6:
719       st->sol = IPPROTO_IPV6;
720       st->so_mtu_discover = IPV6_MTU_DISCOVER;
721       st->so_mtu = IPV6_MTU;
722       st->hdrlen = 48;
723       break;
724     default:
725       errno = EPFNOSUPPORT;
726       return (-1);
727   }
728
729   /* Snaffle the UDP socket. */
730   st->sk = sk;
731
732   /* Turn on kernel path-MTU discovery and force DF on. */
733   i = IP_PMTUDISC_PROBE;
734   if (setsockopt(st->sk, st->sol, st->so_mtu_discover, &i, sizeof(i)))
735     return (-1);
736
737   /* Read the initial MTU guess back and report it. */
738   sz = sizeof(mtu);
739   if (getsockopt(st->sk, st->sol, st->so_mtu, &mtu, &sz))
740     return (-1);
741
742   /* Done. */
743   return (mtu);
744 }
745
746 static void linux_finish(void *stv) { ; }
747
748 static void linux_selprep(void *stv, int *maxfd, fd_set *fd_in)
749   { struct linux_state *st = stv; ADDFD(st->sk); }
750
751 static int linux_xmit(void *stv, int mtu)
752 {
753   struct linux_state *st = stv;
754
755   /* Write the packet. */
756   if (write(st->sk, buf, mtu - st->hdrlen) >= 0) return (RC_OK);
757   else if (errno == EMSGSIZE) return (RC_LOWER);
758   else return (RC_FAIL);
759 }
760
761 static int linux_selproc(void *stv, fd_set *fd_in, struct probestate *ps)
762 {
763   struct linux_state *st = stv;
764   int mtu;
765   socklen_t sz;
766   ssize_t n;
767   unsigned char b[65536];
768
769   /* Read an answer.  If it looks like the right kind of error then report a
770    * success.  This is potentially wrong, since we can't tell whether an
771    * error was delayed from an earlier probe.  However, we never return
772    * RC_LOWER from this method, so the packet sizes ought to be monotonically
773    * decreasing and this won't cause trouble.  Otherwise update from the
774    * kernel's idea of the right MTU.
775    */
776   if (FD_ISSET(st->sk, fd_in)) {
777     n = read(st->sk, &buf, sizeof(buf));
778     if (n >= 0 ?
779         mypacketp(ps, b, n) :
780         errno == ECONNREFUSED || errno == EHOSTUNREACH)
781       return (RC_HIGHER);
782     sz = sizeof(mtu);
783     if (getsockopt(st->sk, st->sol, st->so_mtu, &mtu, &sz))
784       return (RC_FAIL);
785     return (mtu);
786   }
787   return (RC_OK);
788 }
789
790 static const struct probe_ops linux_ops = {
791   "linux", OPS_CHAIN, sizeof(struct linux_state),
792   linux_setup, linux_finish,
793   linux_selprep, linux_xmit, linux_selproc
794 };
795
796 #undef OPS_CHAIN
797 #define OPS_CHAIN &linux_ops
798
799 #endif
800
801 /*----- Help options ------------------------------------------------------*/
802
803 static const struct probe_ops *probe_ops = OPS_CHAIN;
804
805 static void version(FILE *fp)
806   { pquis(fp, "$, TrIPE version " VERSION "\n"); }
807
808 static void usage(FILE *fp)
809 {
810   pquis(fp, "Usage: $ [-46v] [-H HEADER] [-m METHOD]\n\
811          [-r SECS] [-g FACTOR] [-t SECS] HOST [PORT]\n");
812 }
813
814 static void help(FILE *fp)
815 {
816   const struct probe_ops *ops;
817
818   version(fp);
819   fputc('\n', fp);
820   usage(fp);
821   fputs("\
822 \n\
823 Options in full:\n\
824 \n\
825 -h, --help              Show this help text.\n\
826 -V, --version           Show version number.\n\
827 -u, --usage             Show brief usage message.\n\
828 \n\
829 -4, --ipv4              Restrict to IPv4 only.\n\
830 -6, --ipv6              Restrict to IPv6 only.\n\
831 -g, --growth=FACTOR     Growth factor for retransmit interval.\n\
832 -m, --method=METHOD     Use METHOD to probe for MTU.\n\
833 -r, --retransmit=SECS   Retransmit if no reply after SEC.\n\
834 -t, --timeout=SECS      Give up expecting a reply after SECS.\n\
835 -v, --verbose           Write a running commentary to stderr.\n\
836 -H, --header=HEX        Packet header, in hexadecimal.\n\
837 \n\
838 Probe methods:\n\
839 ", fp);
840   for (ops = probe_ops; ops; ops = ops->next)
841     printf("\t%s\n", ops->name);
842 }
843
844 /*----- Main code ---------------------------------------------------------*/
845
846 int main(int argc, char *argv[])
847 {
848   struct param pp = { 0, 0.333, 3.0, 8.0, 0, OPS_CHAIN };
849   hex_ctx hc;
850   dstr d = DSTR_INIT;
851   size_t sz;
852   int i, err;
853   struct addrinfo aihint = { 0 }, *ailist, *ai;
854   const char *host, *svc = "7";
855   unsigned f = 0;
856
857 #define f_bogus 1u
858
859   if ((rawicmp = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0 ||
860       (rawudp = socket(PF_INET, SOCK_RAW, IPPROTO_UDP)) < 0)
861     rawerr = errno;
862   if (setuid(getuid()))
863     abort();
864
865   ego(argv[0]);
866   fillbuffer(buf, sizeof(buf));
867
868   aihint.ai_family = AF_UNSPEC;
869   aihint.ai_protocol = IPPROTO_UDP;
870   aihint.ai_socktype = SOCK_DGRAM;
871   aihint.ai_flags = AI_ADDRCONFIG;
872
873   for (;;) {
874     static const struct option opts[] = {
875       { "help",         0,              0,      'h' },
876       { "version",      0,              0,      'V' },
877       { "usage",        0,              0,      'u' },
878       { "ipv4",         0,              0,      '4' },
879       { "ipv6",         0,              0,      '6' },
880       { "header",       OPTF_ARGREQ,    0,      'H' },
881       { "growth",       OPTF_ARGREQ,    0,      'g' },
882       { "method",       OPTF_ARGREQ,    0,      'm' },
883       { "retransmit",   OPTF_ARGREQ,    0,      'r' },
884       { "timeout",      OPTF_ARGREQ,    0,      't' },
885       { "verbose",      0,              0,      'v' },
886       { 0,              0,              0,      0 }
887     };
888
889     i = mdwopt(argc, argv, "hVu" "46H:g:m:r:t:v", opts, 0, 0, 0);
890     if (i < 0) break;
891     switch (i) {
892       case 'h': help(stdout); exit(0);
893       case 'V': version(stdout); exit(0);
894       case 'u': usage(stdout); exit(0);
895
896       case 'H':
897         DRESET(&d);
898         hex_init(&hc);
899         hex_decode(&hc, optarg, strlen(optarg), &d);
900         hex_decode(&hc, 0, 0, &d);
901         sz = d.len < 532 ? d.len : 532;
902         memcpy(buf, d.buf, sz);
903         pp.seqoff = sz;
904         break;
905
906       case '4': aihint.ai_family = AF_INET; break;
907       case '6': aihint.ai_family = AF_INET6; break;
908       case 'g': pp.regr = s2f(optarg, "retransmit growth factor"); break;
909       case 'r': pp.retx = s2f(optarg, "retransmit interval"); break;
910       case 't': pp.timeout = s2f(optarg, "timeout"); break;
911
912       case 'm':
913         for (pp.pops = OPS_CHAIN; pp.pops; pp.pops = pp.pops->next)
914           if (strcmp(pp.pops->name, optarg) == 0) goto found_alg;
915         die(EXIT_FAILURE, "unknown probe algorithm `%s'", optarg);
916       found_alg:
917         break;
918
919       case 'v': pp.f |= F_VERBOSE; break;
920
921       default:
922         f |= f_bogus;
923         break;
924     }
925   }
926   argv += optind; argc -= optind;
927   if ((f & f_bogus) || 1 > argc || argc > 2) {
928     usage(stderr);
929     exit(EXIT_FAILURE);
930   }
931
932   host = argv[0];
933   if (argv[1]) svc = argv[1];
934   if ((err = getaddrinfo(host, svc, &aihint, &ailist)) != 0) {
935     die(EXIT_FAILURE, "unknown host `%s' or service `%s': %s",
936         host, svc, gai_strerror(err));
937   }
938   for (ai = ailist; ai && !addrfamok(ai->ai_family); ai = ai->ai_next);
939   if (!ai) die(EXIT_FAILURE, "no supported address families for `%s'", host);
940   assert(ai->ai_addrlen <= sizeof(pp.a));
941   memcpy(&pp.a, ai->ai_addr, ai->ai_addrlen);
942
943   i = pathmtu(&pp);
944   if (i < 0)
945     die(EXIT_FAILURE, "failed to discover MTU: %s", strerror(errno));
946   printf("%d\n", i);
947   if (ferror(stdout) || fflush(stdout) || fclose(stdout))
948     die(EXIT_FAILURE, "failed to write result: %s", strerror(errno));
949   return (0);
950 }
951
952 /*----- That's all, folks -------------------------------------------------*/