- if (ndspi->ndspi_prev != NULL) {
- if (new_snapend <= ndspi->ndspi_prev->ndspi_snapend)
- ndo->ndo_snapend = new_snapend;
- } else {
- if (new_snapend < ndo->ndo_snapend)
- ndo->ndo_snapend = new_snapend;
+ if (ndspi->ndspi_prev != NULL)
+ previous_snapend = ndspi->ndspi_prev->ndspi_snapend;
+ else
+ previous_snapend = ndo->ndo_snapend;
+
+ /*
+ * Find out how many bytes remain after the previous
+ * snapend - or, if there is no previous snapend, after
+ * the current snapend.
+ *
+ * We're restricted to packets with at most UINT_MAX bytes;
+ * cast the result to u_int, so that we don't get truncation
+ * warnings on LP64 and LLP64 platforms. (ptrdiff_t is
+ * signed and we want an unsigned difference; the pointer
+ * should at most be equal to snapend, and must *never*
+ * be past snapend.)
+ */
+ snaplen_remaining = (u_int)(previous_snapend - bp);
+
+ /*
+ * If the new snapend is smaller than the one calculated
+ * above, set the snapend to that value, otherwise leave
+ * it unchanged.
+ */
+ if (newlen <= snaplen_remaining) {
+ /* Snapend isn't past the previous snapend */
+ ndo->ndo_snapend = bp + newlen;