+// adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
+void adjust_tcp_mss(sessionidt s, tunnelidt t, uint8_t *buf, int len, uint8_t *tcp)
+{
+ int d = (tcp[12] >> 4) * 4;
+ uint8_t *mss = 0;
+ uint8_t *opts;
+ uint8_t *data;
+ uint16_t orig;
+ uint32_t sum;
+
+ if ((tcp[13] & 0x3f) & ~(TCP_FLAG_SYN|TCP_FLAG_ACK)) // only want SYN and SYN,ACK
+ return;
+
+ if (tcp + d > buf + len) // short?
+ return;
+
+ opts = tcp + 20;
+ data = tcp + d;
+
+ while (opts < data)
+ {
+ if (*opts == 2 && opts[1] == 4) // mss option (2), length 4
+ {
+ mss = opts + 2;
+ if (mss + 2 > data) return; // short?
+ break;
+ }
+
+ if (*opts == 0) return; // end of options
+ if (*opts == 1 || !opts[1]) // no op (one byte), or no length (prevent loop)
+ opts++;
+ else
+ opts += opts[1]; // skip over option
+ }
+
+ if (!mss) return; // not found
+ orig = ntohs(*(uint16_t *) mss);
+
+ if (orig <= MSS) return; // mss OK
+
+ LOG(5, s, t, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
+ fmtaddr(*(in_addr_t *) (buf + 12), 0), ntohs(*(uint16_t *) tcp),
+ fmtaddr(*(in_addr_t *) (buf + 16), 1), ntohs(*(uint16_t *) (tcp + 2)),
+ (tcp[13] & TCP_FLAG_ACK) ? ",ACK" : "", orig, MSS);
+
+ // set mss
+ *(int16_t *) mss = htons(MSS);
+
+ // adjust checksum (see rfc1141)
+ sum = orig + (~MSS & 0xffff);
+ sum += ntohs(*(uint16_t *) (tcp + 16));
+ sum = (sum & 0xffff) + (sum >> 16);
+ *(uint16_t *) (tcp + 16) = htons(sum + (sum >> 16));
+}
+