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