+static int
+parse_ipv6(struct ofpbuf *packet, struct flow *flow)
+{
+ struct ip6_hdr *nh;
+ int nh_len = sizeof(struct ip6_hdr);
+ int payload_len;
+ ovs_be32 tc_flow;
+ int nexthdr;
+
+ if (packet->size < sizeof *nh) {
+ return -EINVAL;
+ }
+
+ nh = packet->data;
+ nexthdr = nh->ip6_nxt;
+ payload_len = ntohs(nh->ip6_plen);
+
+ flow->ipv6_src = nh->ip6_src;
+ flow->ipv6_dst = nh->ip6_dst;
+
+ tc_flow = get_unaligned_be32(&nh->ip6_flow);
+ flow->nw_tos = (ntohl(tc_flow) >> 4) & IP_DSCP_MASK;
+ flow->nw_proto = IPPROTO_NONE;
+
+ /* We don't process jumbograms. */
+ if (!payload_len) {
+ return -EINVAL;
+ }
+
+ if (packet->size < sizeof *nh + payload_len) {
+ return -EINVAL;
+ }
+
+ while (1) {
+ if ((nexthdr != IPPROTO_HOPOPTS)
+ && (nexthdr != IPPROTO_ROUTING)
+ && (nexthdr != IPPROTO_DSTOPTS)
+ && (nexthdr != IPPROTO_AH)
+ && (nexthdr != IPPROTO_FRAGMENT)) {
+ /* It's either a terminal header (e.g., TCP, UDP) or one we
+ * don't understand. In either case, we're done with the
+ * packet, so use it to fill in 'nw_proto'. */
+ break;
+ }
+
+ /* We only verify that at least 8 bytes of the next header are
+ * available, but many of these headers are longer. Ensure that
+ * accesses within the extension header are within those first 8
+ * bytes. */
+ if (packet->size < nh_len + 8) {
+ return -EINVAL;
+ }
+
+ if ((nexthdr == IPPROTO_HOPOPTS)
+ || (nexthdr == IPPROTO_ROUTING)
+ || (nexthdr == IPPROTO_DSTOPTS)) {
+ /* These headers, while different, have the fields we care about
+ * in the same location and with the same interpretation. */
+ struct ip6_ext *ext_hdr;
+
+ ext_hdr = (struct ip6_ext *)((char *)packet->data + nh_len);
+ nexthdr = ext_hdr->ip6e_nxt;
+ nh_len += (ext_hdr->ip6e_len + 1) * 8;
+ } else if (nexthdr == IPPROTO_AH) {
+ /* A standard AH definition isn't available, but the fields
+ * we care about are in the same location as the generic
+ * option header--only the header length is calculated
+ * differently. */
+ struct ip6_ext *ext_hdr;
+
+ ext_hdr = (struct ip6_ext *)((char *)packet->data + nh_len);
+ nexthdr = ext_hdr->ip6e_nxt;
+ nh_len += (ext_hdr->ip6e_len + 2) * 4;
+ } else if (nexthdr == IPPROTO_FRAGMENT) {
+ struct ip6_frag *frag_hdr;
+
+ frag_hdr = (struct ip6_frag *)((char *)packet->data + nh_len);
+
+ nexthdr = frag_hdr->ip6f_nxt;
+ nh_len += sizeof *frag_hdr;
+
+ /* We only process the first fragment. */
+ if ((frag_hdr->ip6f_offlg & IP6F_OFF_MASK) != htons(0)) {
+ nexthdr = IPPROTO_FRAGMENT;
+ break;
+ }
+ }
+ }
+
+ /* The payload length claims to be smaller than the size of the
+ * headers we've already processed. */
+ if (payload_len < nh_len - sizeof *nh) {
+ return -EINVAL;
+ }
+
+ flow->nw_proto = nexthdr;
+ return nh_len;
+}
+