packets: Rename "rco_flags" to "rso_flags".
[cascardo/ovs.git] / lib / packets.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "packets.h"
19 #include <arpa/inet.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <netinet/ip6.h>
23 #include <netinet/icmp6.h>
24 #include <stdlib.h>
25 #include "byte-order.h"
26 #include "csum.h"
27 #include "crc32c.h"
28 #include "flow.h"
29 #include "hmap.h"
30 #include "openvswitch/dynamic-string.h"
31 #include "ovs-thread.h"
32 #include "odp-util.h"
33 #include "dp-packet.h"
34 #include "unaligned.h"
35
36 const struct in6_addr in6addr_exact = IN6ADDR_EXACT_INIT;
37 const struct in6_addr in6addr_all_hosts = IN6ADDR_ALL_HOSTS_INIT;
38
39 struct in6_addr
40 flow_tnl_dst(const struct flow_tnl *tnl)
41 {
42     return tnl->ip_dst ? in6_addr_mapped_ipv4(tnl->ip_dst) : tnl->ipv6_dst;
43 }
44
45 struct in6_addr
46 flow_tnl_src(const struct flow_tnl *tnl)
47 {
48     return tnl->ip_src ? in6_addr_mapped_ipv4(tnl->ip_src) : tnl->ipv6_src;
49 }
50
51 /* Parses 's' as a 16-digit hexadecimal number representing a datapath ID.  On
52  * success stores the dpid into '*dpidp' and returns true, on failure stores 0
53  * into '*dpidp' and returns false.
54  *
55  * Rejects an all-zeros dpid as invalid. */
56 bool
57 dpid_from_string(const char *s, uint64_t *dpidp)
58 {
59     *dpidp = (strlen(s) == 16 && strspn(s, "0123456789abcdefABCDEF") == 16
60               ? strtoull(s, NULL, 16)
61               : 0);
62     return *dpidp != 0;
63 }
64
65 /* Returns true if 'ea' is a reserved address, that a bridge must never
66  * forward, false otherwise.
67  *
68  * If you change this function's behavior, please update corresponding
69  * documentation in vswitch.xml at the same time. */
70 bool
71 eth_addr_is_reserved(const struct eth_addr ea)
72 {
73     struct eth_addr_node {
74         struct hmap_node hmap_node;
75         const uint64_t ea64;
76     };
77
78     static struct eth_addr_node nodes[] = {
79         /* STP, IEEE pause frames, and other reserved protocols. */
80         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000000ULL },
81         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000001ULL },
82         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000002ULL },
83         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000003ULL },
84         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000004ULL },
85         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000005ULL },
86         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000006ULL },
87         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000007ULL },
88         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000008ULL },
89         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000009ULL },
90         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000aULL },
91         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000bULL },
92         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000cULL },
93         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000dULL },
94         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000eULL },
95         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000fULL },
96
97         /* Extreme protocols. */
98         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000000ULL }, /* EDP. */
99         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000004ULL }, /* EAPS. */
100         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000006ULL }, /* EAPS. */
101
102         /* Cisco protocols. */
103         { HMAP_NODE_NULL_INITIALIZER, 0x01000c000000ULL }, /* ISL. */
104         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccccULL }, /* PAgP, UDLD, CDP,
105                                                             * DTP, VTP. */
106         { HMAP_NODE_NULL_INITIALIZER, 0x01000ccccccdULL }, /* PVST+. */
107         { HMAP_NODE_NULL_INITIALIZER, 0x01000ccdcdcdULL }, /* STP Uplink Fast,
108                                                             * FlexLink. */
109
110         /* Cisco CFM. */
111         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc0ULL },
112         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc1ULL },
113         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc2ULL },
114         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc3ULL },
115         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc4ULL },
116         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc5ULL },
117         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc6ULL },
118         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc7ULL },
119     };
120
121     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
122     struct eth_addr_node *node;
123     static struct hmap addrs;
124     uint64_t ea64;
125
126     if (ovsthread_once_start(&once)) {
127         hmap_init(&addrs);
128         for (node = nodes; node < &nodes[ARRAY_SIZE(nodes)]; node++) {
129             hmap_insert(&addrs, &node->hmap_node, hash_uint64(node->ea64));
130         }
131         ovsthread_once_done(&once);
132     }
133
134     ea64 = eth_addr_to_uint64(ea);
135     HMAP_FOR_EACH_IN_BUCKET (node, hmap_node, hash_uint64(ea64), &addrs) {
136         if (node->ea64 == ea64) {
137             return true;
138         }
139     }
140     return false;
141 }
142
143 bool
144 eth_addr_from_string(const char *s, struct eth_addr *ea)
145 {
146     if (ovs_scan(s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(*ea))) {
147         return true;
148     } else {
149         *ea = eth_addr_zero;
150         return false;
151     }
152 }
153
154 /* Fills 'b' with a Reverse ARP packet with Ethernet source address 'eth_src'.
155  * This function is used by Open vSwitch to compose packets in cases where
156  * context is important but content doesn't (or shouldn't) matter.
157  *
158  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
159  * desired. */
160 void
161 compose_rarp(struct dp_packet *b, const struct eth_addr eth_src)
162 {
163     struct eth_header *eth;
164     struct arp_eth_header *arp;
165
166     dp_packet_clear(b);
167     dp_packet_prealloc_tailroom(b, 2 + ETH_HEADER_LEN + VLAN_HEADER_LEN
168                              + ARP_ETH_HEADER_LEN);
169     dp_packet_reserve(b, 2 + VLAN_HEADER_LEN);
170     eth = dp_packet_put_uninit(b, sizeof *eth);
171     eth->eth_dst = eth_addr_broadcast;
172     eth->eth_src = eth_src;
173     eth->eth_type = htons(ETH_TYPE_RARP);
174
175     arp = dp_packet_put_uninit(b, sizeof *arp);
176     arp->ar_hrd = htons(ARP_HRD_ETHERNET);
177     arp->ar_pro = htons(ARP_PRO_IP);
178     arp->ar_hln = sizeof arp->ar_sha;
179     arp->ar_pln = sizeof arp->ar_spa;
180     arp->ar_op = htons(ARP_OP_RARP);
181     arp->ar_sha = eth_src;
182     put_16aligned_be32(&arp->ar_spa, htonl(0));
183     arp->ar_tha = eth_src;
184     put_16aligned_be32(&arp->ar_tpa, htonl(0));
185
186     dp_packet_reset_offsets(b);
187     dp_packet_set_l3(b, arp);
188 }
189
190 /* Insert VLAN header according to given TCI. Packet passed must be Ethernet
191  * packet.  Ignores the CFI bit of 'tci' using 0 instead.
192  *
193  * Also adjusts the layer offsets accordingly. */
194 void
195 eth_push_vlan(struct dp_packet *packet, ovs_be16 tpid, ovs_be16 tci)
196 {
197     struct vlan_eth_header *veh;
198
199     /* Insert new 802.1Q header. */
200     veh = dp_packet_resize_l2(packet, VLAN_HEADER_LEN);
201     memmove(veh, (char *)veh + VLAN_HEADER_LEN, 2 * ETH_ADDR_LEN);
202     veh->veth_type = tpid;
203     veh->veth_tci = tci & htons(~VLAN_CFI);
204 }
205
206 /* Removes outermost VLAN header (if any is present) from 'packet'.
207  *
208  * 'packet->l2_5' should initially point to 'packet''s outer-most VLAN header
209  * or may be NULL if there are no VLAN headers. */
210 void
211 eth_pop_vlan(struct dp_packet *packet)
212 {
213     struct vlan_eth_header *veh = dp_packet_l2(packet);
214
215     if (veh && dp_packet_size(packet) >= sizeof *veh
216         && eth_type_vlan(veh->veth_type)) {
217
218         memmove((char *)veh + VLAN_HEADER_LEN, veh, 2 * ETH_ADDR_LEN);
219         dp_packet_resize_l2(packet, -VLAN_HEADER_LEN);
220     }
221 }
222
223 /* Set ethertype of the packet. */
224 static void
225 set_ethertype(struct dp_packet *packet, ovs_be16 eth_type)
226 {
227     struct eth_header *eh = dp_packet_l2(packet);
228
229     if (!eh) {
230         return;
231     }
232
233     if (eth_type_vlan(eh->eth_type)) {
234         ovs_be16 *p;
235         char *l2_5 = dp_packet_l2_5(packet);
236
237         p = ALIGNED_CAST(ovs_be16 *,
238                          (l2_5 ? l2_5 : (char *)dp_packet_l3(packet)) - 2);
239         *p = eth_type;
240     } else {
241         eh->eth_type = eth_type;
242     }
243 }
244
245 static bool is_mpls(struct dp_packet *packet)
246 {
247     return packet->l2_5_ofs != UINT16_MAX;
248 }
249
250 /* Set time to live (TTL) of an MPLS label stack entry (LSE). */
251 void
252 set_mpls_lse_ttl(ovs_be32 *lse, uint8_t ttl)
253 {
254     *lse &= ~htonl(MPLS_TTL_MASK);
255     *lse |= htonl((ttl << MPLS_TTL_SHIFT) & MPLS_TTL_MASK);
256 }
257
258 /* Set traffic class (TC) of an MPLS label stack entry (LSE). */
259 void
260 set_mpls_lse_tc(ovs_be32 *lse, uint8_t tc)
261 {
262     *lse &= ~htonl(MPLS_TC_MASK);
263     *lse |= htonl((tc << MPLS_TC_SHIFT) & MPLS_TC_MASK);
264 }
265
266 /* Set label of an MPLS label stack entry (LSE). */
267 void
268 set_mpls_lse_label(ovs_be32 *lse, ovs_be32 label)
269 {
270     *lse &= ~htonl(MPLS_LABEL_MASK);
271     *lse |= htonl((ntohl(label) << MPLS_LABEL_SHIFT) & MPLS_LABEL_MASK);
272 }
273
274 /* Set bottom of stack (BoS) bit of an MPLS label stack entry (LSE). */
275 void
276 set_mpls_lse_bos(ovs_be32 *lse, uint8_t bos)
277 {
278     *lse &= ~htonl(MPLS_BOS_MASK);
279     *lse |= htonl((bos << MPLS_BOS_SHIFT) & MPLS_BOS_MASK);
280 }
281
282 /* Compose an MPLS label stack entry (LSE) from its components:
283  * label, traffic class (TC), time to live (TTL) and
284  * bottom of stack (BoS) bit. */
285 ovs_be32
286 set_mpls_lse_values(uint8_t ttl, uint8_t tc, uint8_t bos, ovs_be32 label)
287 {
288     ovs_be32 lse = htonl(0);
289     set_mpls_lse_ttl(&lse, ttl);
290     set_mpls_lse_tc(&lse, tc);
291     set_mpls_lse_bos(&lse, bos);
292     set_mpls_lse_label(&lse, label);
293     return lse;
294 }
295
296 /* Set MPLS label stack entry to outermost MPLS header.*/
297 void
298 set_mpls_lse(struct dp_packet *packet, ovs_be32 mpls_lse)
299 {
300     /* Packet type should be MPLS to set label stack entry. */
301     if (is_mpls(packet)) {
302         struct mpls_hdr *mh = dp_packet_l2_5(packet);
303
304         /* Update mpls label stack entry. */
305         put_16aligned_be32(&mh->mpls_lse, mpls_lse);
306     }
307 }
308
309 /* Push MPLS label stack entry 'lse' onto 'packet' as the outermost MPLS
310  * header.  If 'packet' does not already have any MPLS labels, then its
311  * Ethertype is changed to 'ethtype' (which must be an MPLS Ethertype). */
312 void
313 push_mpls(struct dp_packet *packet, ovs_be16 ethtype, ovs_be32 lse)
314 {
315     char * header;
316     size_t len;
317
318     if (!eth_type_mpls(ethtype)) {
319         return;
320     }
321
322     if (!is_mpls(packet)) {
323         /* Set MPLS label stack offset. */
324         packet->l2_5_ofs = packet->l3_ofs;
325     }
326
327     set_ethertype(packet, ethtype);
328
329     /* Push new MPLS shim header onto packet. */
330     len = packet->l2_5_ofs;
331     header = dp_packet_resize_l2_5(packet, MPLS_HLEN);
332     memmove(header, header + MPLS_HLEN, len);
333     memcpy(header + len, &lse, sizeof lse);
334 }
335
336 /* If 'packet' is an MPLS packet, removes its outermost MPLS label stack entry.
337  * If the label that was removed was the only MPLS label, changes 'packet''s
338  * Ethertype to 'ethtype' (which ordinarily should not be an MPLS
339  * Ethertype). */
340 void
341 pop_mpls(struct dp_packet *packet, ovs_be16 ethtype)
342 {
343     if (is_mpls(packet)) {
344         struct mpls_hdr *mh = dp_packet_l2_5(packet);
345         size_t len = packet->l2_5_ofs;
346
347         set_ethertype(packet, ethtype);
348         if (get_16aligned_be32(&mh->mpls_lse) & htonl(MPLS_BOS_MASK)) {
349             dp_packet_set_l2_5(packet, NULL);
350         }
351         /* Shift the l2 header forward. */
352         memmove((char*)dp_packet_data(packet) + MPLS_HLEN, dp_packet_data(packet), len);
353         dp_packet_resize_l2_5(packet, -MPLS_HLEN);
354     }
355 }
356
357 /* Converts hex digits in 'hex' to an Ethernet packet in '*packetp'.  The
358  * caller must free '*packetp'.  On success, returns NULL.  On failure, returns
359  * an error message and stores NULL in '*packetp'.
360  *
361  * Aligns the L3 header of '*packetp' on a 32-bit boundary. */
362 const char *
363 eth_from_hex(const char *hex, struct dp_packet **packetp)
364 {
365     struct dp_packet *packet;
366
367     /* Use 2 bytes of headroom to 32-bit align the L3 header. */
368     packet = *packetp = dp_packet_new_with_headroom(strlen(hex) / 2, 2);
369
370     if (dp_packet_put_hex(packet, hex, NULL)[0] != '\0') {
371         dp_packet_delete(packet);
372         *packetp = NULL;
373         return "Trailing garbage in packet data";
374     }
375
376     if (dp_packet_size(packet) < ETH_HEADER_LEN) {
377         dp_packet_delete(packet);
378         *packetp = NULL;
379         return "Packet data too short for Ethernet";
380     }
381
382     return NULL;
383 }
384
385 void
386 eth_format_masked(const struct eth_addr eth,
387                   const struct eth_addr *mask, struct ds *s)
388 {
389     ds_put_format(s, ETH_ADDR_FMT, ETH_ADDR_ARGS(eth));
390     if (mask && !eth_mask_is_exact(*mask)) {
391         ds_put_format(s, "/"ETH_ADDR_FMT, ETH_ADDR_ARGS(*mask));
392     }
393 }
394
395 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
396  * that it specifies, that is, the number of 1-bits in 'netmask'.
397  *
398  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
399  * still be in the valid range but isn't otherwise meaningful. */
400 int
401 ip_count_cidr_bits(ovs_be32 netmask)
402 {
403     return 32 - ctz32(ntohl(netmask));
404 }
405
406 void
407 ip_format_masked(ovs_be32 ip, ovs_be32 mask, struct ds *s)
408 {
409     ds_put_format(s, IP_FMT, IP_ARGS(ip));
410     if (mask != OVS_BE32_MAX) {
411         if (ip_is_cidr(mask)) {
412             ds_put_format(s, "/%d", ip_count_cidr_bits(mask));
413         } else {
414             ds_put_format(s, "/"IP_FMT, IP_ARGS(mask));
415         }
416     }
417 }
418
419 /* Parses string 's', which must be an IP address.  Stores the IP address into
420  * '*ip'.  Returns true if successful, otherwise false. */
421 bool
422 ip_parse(const char *s, ovs_be32 *ip)
423 {
424     return inet_pton(AF_INET, s, ip) == 1;
425 }
426
427 /* Parses string 's', which must be an IP address with an optional netmask or
428  * CIDR prefix length.  Stores the IP address into '*ip', netmask into '*mask',
429  * (255.255.255.255, if 's' lacks a netmask), and number of scanned characters
430  * into '*n'.
431  *
432  * Returns NULL if successful, otherwise an error message that the caller must
433  * free(). */
434 char * OVS_WARN_UNUSED_RESULT
435 ip_parse_masked_len(const char *s, int *n, ovs_be32 *ip,
436                     ovs_be32 *mask)
437 {
438     int prefix;
439
440     if (ovs_scan_len(s, n, IP_SCAN_FMT"/"IP_SCAN_FMT,
441                  IP_SCAN_ARGS(ip), IP_SCAN_ARGS(mask))) {
442         /* OK. */
443     } else if (ovs_scan_len(s, n, IP_SCAN_FMT"/%d",
444                             IP_SCAN_ARGS(ip), &prefix)) {
445         if (prefix < 0 || prefix > 32) {
446             return xasprintf("%s: IPv4 network prefix bits not between 0 and "
447                               "32, inclusive", s);
448         }
449         *mask = be32_prefix_mask(prefix);
450     } else if (ovs_scan_len(s, n, IP_SCAN_FMT, IP_SCAN_ARGS(ip))) {
451         *mask = OVS_BE32_MAX;
452     } else {
453         return xasprintf("%s: invalid IP address", s);
454     }
455     return NULL;
456 }
457
458 /* This function is similar to ip_parse_masked_len(), but doesn't return the
459  * number of scanned characters and expects 's' to end after the ip/(optional)
460  * mask.
461  *
462  * Returns NULL if successful, otherwise an error message that the caller must
463  * free(). */
464 char * OVS_WARN_UNUSED_RESULT
465 ip_parse_masked(const char *s, ovs_be32 *ip, ovs_be32 *mask)
466 {
467     int n = 0;
468
469     char *error = ip_parse_masked_len(s, &n, ip, mask);
470     if (!error && s[n]) {
471         return xasprintf("%s: invalid IP address", s);
472     }
473     return error;
474 }
475
476 /* Similar to ip_parse_masked_len(), but the mask, if present, must be a CIDR
477  * mask and is returned as a prefix len in '*plen'. */
478 char * OVS_WARN_UNUSED_RESULT
479 ip_parse_cidr_len(const char *s, int *n, ovs_be32 *ip, unsigned int *plen)
480 {
481     ovs_be32 mask;
482     char *error;
483
484     error = ip_parse_masked_len(s, n, ip, &mask);
485     if (error) {
486         return error;
487     }
488
489     if (!ip_is_cidr(mask)) {
490         return xasprintf("%s: CIDR network required", s);
491     }
492     *plen = ip_count_cidr_bits(mask);
493     return NULL;
494 }
495
496 /* Similar to ip_parse_cidr_len(), but doesn't return the number of scanned
497  * characters and expects 's' to be NULL terminated at the end of the
498  * ip/(optional) cidr. */
499 char * OVS_WARN_UNUSED_RESULT
500 ip_parse_cidr(const char *s, ovs_be32 *ip, unsigned int *plen)
501 {
502     int n = 0;
503
504     char *error = ip_parse_cidr_len(s, &n, ip, plen);
505     if (!error && s[n]) {
506         return xasprintf("%s: invalid IP address", s);
507     }
508     return error;
509 }
510
511 /* Parses string 's', which must be an IPv6 address.  Stores the IPv6 address
512  * into '*ip'.  Returns true if successful, otherwise false. */
513 bool
514 ipv6_parse(const char *s, struct in6_addr *ip)
515 {
516     return inet_pton(AF_INET6, s, ip) == 1;
517 }
518
519 /* Parses string 's', which must be an IPv6 address with an optional netmask or
520  * CIDR prefix length.  Stores the IPv6 address into '*ip' and the netmask into
521  * '*mask' (if 's' does not contain a netmask, all-one-bits is assumed), and
522  * number of scanned characters into '*n'.
523  *
524  * Returns NULL if successful, otherwise an error message that the caller must
525  * free(). */
526 char * OVS_WARN_UNUSED_RESULT
527 ipv6_parse_masked_len(const char *s, int *n, struct in6_addr *ip,
528                       struct in6_addr *mask)
529 {
530     char ipv6_s[IPV6_SCAN_LEN + 1];
531     int prefix;
532
533     if (ovs_scan_len(s, n, " "IPV6_SCAN_FMT, ipv6_s)
534         && ipv6_parse(ipv6_s, ip)) {
535         if (ovs_scan_len(s, n, "/%d", &prefix)) {
536             if (prefix < 0 || prefix > 128) {
537                 return xasprintf("%s: IPv6 network prefix bits not between 0 "
538                                  "and 128, inclusive", s);
539             }
540             *mask = ipv6_create_mask(prefix);
541         } else if (ovs_scan_len(s, n, "/"IPV6_SCAN_FMT, ipv6_s)) {
542              if (!ipv6_parse(ipv6_s, mask)) {
543                  return xasprintf("%s: Invalid IPv6 mask", s);
544              }
545             /* OK. */
546         } else {
547             /* OK. No mask. */
548             *mask = in6addr_exact;
549         }
550         return NULL;
551     }
552     return xasprintf("%s: invalid IPv6 address", s);
553 }
554
555 /* This function is similar to ipv6_parse_masked_len(), but doesn't return the
556  * number of scanned characters and expects 's' to end following the
557  * ipv6/(optional) mask. */
558 char * OVS_WARN_UNUSED_RESULT
559 ipv6_parse_masked(const char *s, struct in6_addr *ip, struct in6_addr *mask)
560 {
561     int n = 0;
562
563     char *error = ipv6_parse_masked_len(s, &n, ip, mask);
564     if (!error && s[n]) {
565         return xasprintf("%s: invalid IPv6 address", s);
566     }
567     return error;
568 }
569
570 /* Similar to ipv6_parse_masked_len(), but the mask, if present, must be a CIDR
571  * mask and is returned as a prefix length in '*plen'. */
572 char * OVS_WARN_UNUSED_RESULT
573 ipv6_parse_cidr_len(const char *s, int *n, struct in6_addr *ip,
574                     unsigned int *plen)
575 {
576     struct in6_addr mask;
577     char *error;
578
579     error = ipv6_parse_masked_len(s, n, ip, &mask);
580     if (error) {
581         return error;
582     }
583
584     if (!ipv6_is_cidr(&mask)) {
585         return xasprintf("%s: IPv6 CIDR network required", s);
586     }
587     *plen = ipv6_count_cidr_bits(&mask);
588     return NULL;
589 }
590
591 /* Similar to ipv6_parse_cidr_len(), but doesn't return the number of scanned
592  * characters and expects 's' to end after the ipv6/(optional) cidr. */
593 char * OVS_WARN_UNUSED_RESULT
594 ipv6_parse_cidr(const char *s, struct in6_addr *ip, unsigned int *plen)
595 {
596     int n = 0;
597
598     char *error = ipv6_parse_cidr_len(s, &n, ip, plen);
599     if (!error && s[n]) {
600         return xasprintf("%s: invalid IPv6 address", s);
601     }
602     return error;
603 }
604
605 /* Stores the string representation of the IPv6 address 'addr' into the
606  * character array 'addr_str', which must be at least INET6_ADDRSTRLEN
607  * bytes long. */
608 void
609 ipv6_format_addr(const struct in6_addr *addr, struct ds *s)
610 {
611     char *dst;
612
613     ds_reserve(s, s->length + INET6_ADDRSTRLEN);
614
615     dst = s->string + s->length;
616     inet_ntop(AF_INET6, addr, dst, INET6_ADDRSTRLEN);
617     s->length += strlen(dst);
618 }
619
620 /* Same as print_ipv6_addr, but optionally encloses the address in square
621  * brackets. */
622 void
623 ipv6_format_addr_bracket(const struct in6_addr *addr, struct ds *s,
624                          bool bracket)
625 {
626     if (bracket) {
627         ds_put_char(s, '[');
628     }
629     ipv6_format_addr(addr, s);
630     if (bracket) {
631         ds_put_char(s, ']');
632     }
633 }
634
635 void
636 ipv6_format_mapped(const struct in6_addr *addr, struct ds *s)
637 {
638     if (IN6_IS_ADDR_V4MAPPED(addr)) {
639         ds_put_format(s, IP_FMT, addr->s6_addr[12], addr->s6_addr[13],
640                                  addr->s6_addr[14], addr->s6_addr[15]);
641     } else {
642         ipv6_format_addr(addr, s);
643     }
644 }
645
646 void
647 ipv6_format_masked(const struct in6_addr *addr, const struct in6_addr *mask,
648                    struct ds *s)
649 {
650     ipv6_format_addr(addr, s);
651     if (mask && !ipv6_mask_is_exact(mask)) {
652         if (ipv6_is_cidr(mask)) {
653             int cidr_bits = ipv6_count_cidr_bits(mask);
654             ds_put_format(s, "/%d", cidr_bits);
655         } else {
656             ds_put_char(s, '/');
657             ipv6_format_addr(mask, s);
658         }
659     }
660 }
661
662 /* Stores the string representation of the IPv6 address 'addr' into the
663  * character array 'addr_str', which must be at least INET6_ADDRSTRLEN
664  * bytes long. If addr is IPv4-mapped, store an IPv4 dotted-decimal string. */
665 const char *
666 ipv6_string_mapped(char *addr_str, const struct in6_addr *addr)
667 {
668     ovs_be32 ip;
669     ip = in6_addr_get_mapped_ipv4(addr);
670     if (ip) {
671         return inet_ntop(AF_INET, &ip, addr_str, INET6_ADDRSTRLEN);
672     } else {
673         return inet_ntop(AF_INET6, addr, addr_str, INET6_ADDRSTRLEN);
674     }
675 }
676
677 #ifdef s6_addr32
678 #define s6_addrX s6_addr32
679 #define IPV6_FOR_EACH(VAR) for (int VAR = 0; VAR < 4; VAR++)
680 #else
681 #define s6_addrX s6_addr
682 #define IPV6_FOR_EACH(VAR) for (int VAR = 0; VAR < 16; VAR++)
683 #endif
684
685 struct in6_addr
686 ipv6_addr_bitand(const struct in6_addr *a, const struct in6_addr *b)
687 {
688    struct in6_addr dst;
689    IPV6_FOR_EACH (i) {
690        dst.s6_addrX[i] = a->s6_addrX[i] & b->s6_addrX[i];
691    }
692    return dst;
693 }
694
695 struct in6_addr
696 ipv6_addr_bitxor(const struct in6_addr *a, const struct in6_addr *b)
697 {
698    struct in6_addr dst;
699    IPV6_FOR_EACH (i) {
700        dst.s6_addrX[i] = a->s6_addrX[i] ^ b->s6_addrX[i];
701    }
702    return dst;
703 }
704
705 bool
706 ipv6_is_zero(const struct in6_addr *a)
707 {
708    IPV6_FOR_EACH (i) {
709        if (a->s6_addrX[i]) {
710            return false;
711        }
712    }
713    return true;
714 }
715
716 /* Returns an in6_addr consisting of 'mask' high-order 1-bits and 128-N
717  * low-order 0-bits. */
718 struct in6_addr
719 ipv6_create_mask(int mask)
720 {
721     struct in6_addr netmask;
722     uint8_t *netmaskp = &netmask.s6_addr[0];
723
724     memset(&netmask, 0, sizeof netmask);
725     while (mask > 8) {
726         *netmaskp = 0xff;
727         netmaskp++;
728         mask -= 8;
729     }
730
731     if (mask) {
732         *netmaskp = 0xff << (8 - mask);
733     }
734
735     return netmask;
736 }
737
738 /* Given the IPv6 netmask 'netmask', returns the number of bits of the IPv6
739  * address that it specifies, that is, the number of 1-bits in 'netmask'.
740  * 'netmask' must be a CIDR netmask (see ipv6_is_cidr()).
741  *
742  * If 'netmask' is not a CIDR netmask (see ipv6_is_cidr()), the return value
743  * will still be in the valid range but isn't otherwise meaningful. */
744 int
745 ipv6_count_cidr_bits(const struct in6_addr *netmask)
746 {
747     int i;
748     int count = 0;
749     const uint8_t *netmaskp = &netmask->s6_addr[0];
750
751     for (i=0; i<16; i++) {
752         if (netmaskp[i] == 0xff) {
753             count += 8;
754         } else {
755             uint8_t nm;
756
757             for(nm = netmaskp[i]; nm; nm <<= 1) {
758                 count++;
759             }
760             break;
761         }
762
763     }
764
765     return count;
766 }
767
768 /* Returns true if 'netmask' is a CIDR netmask, that is, if it consists of N
769  * high-order 1-bits and 128-N low-order 0-bits. */
770 bool
771 ipv6_is_cidr(const struct in6_addr *netmask)
772 {
773     const uint8_t *netmaskp = &netmask->s6_addr[0];
774     int i;
775
776     for (i=0; i<16; i++) {
777         if (netmaskp[i] != 0xff) {
778             uint8_t x = ~netmaskp[i];
779             if (x & (x + 1)) {
780                 return false;
781             }
782             while (++i < 16) {
783                 if (netmaskp[i]) {
784                     return false;
785                 }
786             }
787         }
788     }
789
790     return true;
791 }
792
793 /* Populates 'b' with an Ethernet II packet headed with the given 'eth_dst',
794  * 'eth_src' and 'eth_type' parameters.  A payload of 'size' bytes is allocated
795  * in 'b' and returned.  This payload may be populated with appropriate
796  * information by the caller.  Sets 'b''s 'frame' pointer and 'l3' offset to
797  * the Ethernet header and payload respectively.  Aligns b->l3 on a 32-bit
798  * boundary.
799  *
800  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
801  * desired. */
802 void *
803 eth_compose(struct dp_packet *b, const struct eth_addr eth_dst,
804             const struct eth_addr eth_src, uint16_t eth_type,
805             size_t size)
806 {
807     void *data;
808     struct eth_header *eth;
809
810     dp_packet_clear(b);
811
812     /* The magic 2 here ensures that the L3 header (when it is added later)
813      * will be 32-bit aligned. */
814     dp_packet_prealloc_tailroom(b, 2 + ETH_HEADER_LEN + VLAN_HEADER_LEN + size);
815     dp_packet_reserve(b, 2 + VLAN_HEADER_LEN);
816     eth = dp_packet_put_uninit(b, ETH_HEADER_LEN);
817     data = dp_packet_put_zeros(b, size);
818
819     eth->eth_dst = eth_dst;
820     eth->eth_src = eth_src;
821     eth->eth_type = htons(eth_type);
822
823     dp_packet_reset_offsets(b);
824     dp_packet_set_l3(b, data);
825
826     return data;
827 }
828
829 static void
830 packet_set_ipv4_addr(struct dp_packet *packet,
831                      ovs_16aligned_be32 *addr, ovs_be32 new_addr)
832 {
833     struct ip_header *nh = dp_packet_l3(packet);
834     ovs_be32 old_addr = get_16aligned_be32(addr);
835     size_t l4_size = dp_packet_l4_size(packet);
836
837     if (nh->ip_proto == IPPROTO_TCP && l4_size >= TCP_HEADER_LEN) {
838         struct tcp_header *th = dp_packet_l4(packet);
839
840         th->tcp_csum = recalc_csum32(th->tcp_csum, old_addr, new_addr);
841     } else if (nh->ip_proto == IPPROTO_UDP && l4_size >= UDP_HEADER_LEN ) {
842         struct udp_header *uh = dp_packet_l4(packet);
843
844         if (uh->udp_csum) {
845             uh->udp_csum = recalc_csum32(uh->udp_csum, old_addr, new_addr);
846             if (!uh->udp_csum) {
847                 uh->udp_csum = htons(0xffff);
848             }
849         }
850     }
851     nh->ip_csum = recalc_csum32(nh->ip_csum, old_addr, new_addr);
852     put_16aligned_be32(addr, new_addr);
853 }
854
855 /* Returns true, if packet contains at least one routing header where
856  * segements_left > 0.
857  *
858  * This function assumes that L3 and L4 offsets are set in the packet. */
859 static bool
860 packet_rh_present(struct dp_packet *packet, uint8_t *nexthdr)
861 {
862     const struct ovs_16aligned_ip6_hdr *nh;
863     size_t len;
864     size_t remaining;
865     uint8_t *data = dp_packet_l3(packet);
866
867     remaining = packet->l4_ofs - packet->l3_ofs;
868     if (remaining < sizeof *nh) {
869         return false;
870     }
871     nh = ALIGNED_CAST(struct ovs_16aligned_ip6_hdr *, data);
872     data += sizeof *nh;
873     remaining -= sizeof *nh;
874     *nexthdr = nh->ip6_nxt;
875
876     while (1) {
877         if ((*nexthdr != IPPROTO_HOPOPTS)
878                 && (*nexthdr != IPPROTO_ROUTING)
879                 && (*nexthdr != IPPROTO_DSTOPTS)
880                 && (*nexthdr != IPPROTO_AH)
881                 && (*nexthdr != IPPROTO_FRAGMENT)) {
882             /* It's either a terminal header (e.g., TCP, UDP) or one we
883              * don't understand.  In either case, we're done with the
884              * packet, so use it to fill in 'nw_proto'. */
885             break;
886         }
887
888         /* We only verify that at least 8 bytes of the next header are
889          * available, but many of these headers are longer.  Ensure that
890          * accesses within the extension header are within those first 8
891          * bytes. All extension headers are required to be at least 8
892          * bytes. */
893         if (remaining < 8) {
894             return false;
895         }
896
897         if (*nexthdr == IPPROTO_AH) {
898             /* A standard AH definition isn't available, but the fields
899              * we care about are in the same location as the generic
900              * option header--only the header length is calculated
901              * differently. */
902             const struct ip6_ext *ext_hdr = (struct ip6_ext *)data;
903
904             *nexthdr = ext_hdr->ip6e_nxt;
905             len = (ext_hdr->ip6e_len + 2) * 4;
906         } else if (*nexthdr == IPPROTO_FRAGMENT) {
907             const struct ovs_16aligned_ip6_frag *frag_hdr
908                 = ALIGNED_CAST(struct ovs_16aligned_ip6_frag *, data);
909
910             *nexthdr = frag_hdr->ip6f_nxt;
911             len = sizeof *frag_hdr;
912         } else if (*nexthdr == IPPROTO_ROUTING) {
913             const struct ip6_rthdr *rh = (struct ip6_rthdr *)data;
914
915             if (rh->ip6r_segleft > 0) {
916                 return true;
917             }
918
919             *nexthdr = rh->ip6r_nxt;
920             len = (rh->ip6r_len + 1) * 8;
921         } else {
922             const struct ip6_ext *ext_hdr = (struct ip6_ext *)data;
923
924             *nexthdr = ext_hdr->ip6e_nxt;
925             len = (ext_hdr->ip6e_len + 1) * 8;
926         }
927
928         if (remaining < len) {
929             return false;
930         }
931         remaining -= len;
932         data += len;
933     }
934
935     return false;
936 }
937
938 static void
939 packet_update_csum128(struct dp_packet *packet, uint8_t proto,
940                      ovs_16aligned_be32 addr[4], const ovs_be32 new_addr[4])
941 {
942     size_t l4_size = dp_packet_l4_size(packet);
943
944     if (proto == IPPROTO_TCP && l4_size >= TCP_HEADER_LEN) {
945         struct tcp_header *th = dp_packet_l4(packet);
946
947         th->tcp_csum = recalc_csum128(th->tcp_csum, addr, new_addr);
948     } else if (proto == IPPROTO_UDP && l4_size >= UDP_HEADER_LEN) {
949         struct udp_header *uh = dp_packet_l4(packet);
950
951         if (uh->udp_csum) {
952             uh->udp_csum = recalc_csum128(uh->udp_csum, addr, new_addr);
953             if (!uh->udp_csum) {
954                 uh->udp_csum = htons(0xffff);
955             }
956         }
957     } else if (proto == IPPROTO_ICMPV6 &&
958                l4_size >= sizeof(struct icmp6_header)) {
959         struct icmp6_header *icmp = dp_packet_l4(packet);
960
961         icmp->icmp6_cksum = recalc_csum128(icmp->icmp6_cksum, addr, new_addr);
962     }
963 }
964
965 static void
966 packet_set_ipv6_addr(struct dp_packet *packet, uint8_t proto,
967                      ovs_16aligned_be32 addr[4], const ovs_be32 new_addr[4],
968                      bool recalculate_csum)
969 {
970     if (recalculate_csum) {
971         packet_update_csum128(packet, proto, addr, new_addr);
972     }
973     memcpy(addr, new_addr, sizeof(ovs_be32[4]));
974 }
975
976 static void
977 packet_set_ipv6_flow_label(ovs_16aligned_be32 *flow_label, ovs_be32 flow_key)
978 {
979     ovs_be32 old_label = get_16aligned_be32(flow_label);
980     ovs_be32 new_label = (old_label & htonl(~IPV6_LABEL_MASK)) | flow_key;
981     put_16aligned_be32(flow_label, new_label);
982 }
983
984 static void
985 packet_set_ipv6_tc(ovs_16aligned_be32 *flow_label, uint8_t tc)
986 {
987     ovs_be32 old_label = get_16aligned_be32(flow_label);
988     ovs_be32 new_label = (old_label & htonl(0xF00FFFFF)) | htonl(tc << 20);
989     put_16aligned_be32(flow_label, new_label);
990 }
991
992 /* Modifies the IPv4 header fields of 'packet' to be consistent with 'src',
993  * 'dst', 'tos', and 'ttl'.  Updates 'packet''s L4 checksums as appropriate.
994  * 'packet' must contain a valid IPv4 packet with correctly populated l[347]
995  * markers. */
996 void
997 packet_set_ipv4(struct dp_packet *packet, ovs_be32 src, ovs_be32 dst,
998                 uint8_t tos, uint8_t ttl)
999 {
1000     struct ip_header *nh = dp_packet_l3(packet);
1001
1002     if (get_16aligned_be32(&nh->ip_src) != src) {
1003         packet_set_ipv4_addr(packet, &nh->ip_src, src);
1004     }
1005
1006     if (get_16aligned_be32(&nh->ip_dst) != dst) {
1007         packet_set_ipv4_addr(packet, &nh->ip_dst, dst);
1008     }
1009
1010     if (nh->ip_tos != tos) {
1011         uint8_t *field = &nh->ip_tos;
1012
1013         nh->ip_csum = recalc_csum16(nh->ip_csum, htons((uint16_t) *field),
1014                                     htons((uint16_t) tos));
1015         *field = tos;
1016     }
1017
1018     if (nh->ip_ttl != ttl) {
1019         uint8_t *field = &nh->ip_ttl;
1020
1021         nh->ip_csum = recalc_csum16(nh->ip_csum, htons(*field << 8),
1022                                     htons(ttl << 8));
1023         *field = ttl;
1024     }
1025 }
1026
1027 /* Modifies the IPv6 header fields of 'packet' to be consistent with 'src',
1028  * 'dst', 'traffic class', and 'next hop'.  Updates 'packet''s L4 checksums as
1029  * appropriate. 'packet' must contain a valid IPv6 packet with correctly
1030  * populated l[34] offsets. */
1031 void
1032 packet_set_ipv6(struct dp_packet *packet, const ovs_be32 src[4],
1033                 const ovs_be32 dst[4], uint8_t key_tc, ovs_be32 key_fl,
1034                 uint8_t key_hl)
1035 {
1036     struct ovs_16aligned_ip6_hdr *nh = dp_packet_l3(packet);
1037     uint8_t proto = 0;
1038     bool rh_present;
1039
1040     rh_present = packet_rh_present(packet, &proto);
1041
1042     if (memcmp(&nh->ip6_src, src, sizeof(ovs_be32[4]))) {
1043         packet_set_ipv6_addr(packet, proto, nh->ip6_src.be32, src, true);
1044     }
1045
1046     if (memcmp(&nh->ip6_dst, dst, sizeof(ovs_be32[4]))) {
1047         packet_set_ipv6_addr(packet, proto, nh->ip6_dst.be32, dst,
1048                              !rh_present);
1049     }
1050
1051     packet_set_ipv6_tc(&nh->ip6_flow, key_tc);
1052     packet_set_ipv6_flow_label(&nh->ip6_flow, key_fl);
1053     nh->ip6_hlim = key_hl;
1054 }
1055
1056 static void
1057 packet_set_port(ovs_be16 *port, ovs_be16 new_port, ovs_be16 *csum)
1058 {
1059     if (*port != new_port) {
1060         *csum = recalc_csum16(*csum, *port, new_port);
1061         *port = new_port;
1062     }
1063 }
1064
1065 /* Sets the TCP source and destination port ('src' and 'dst' respectively) of
1066  * the TCP header contained in 'packet'.  'packet' must be a valid TCP packet
1067  * with its l4 offset properly populated. */
1068 void
1069 packet_set_tcp_port(struct dp_packet *packet, ovs_be16 src, ovs_be16 dst)
1070 {
1071     struct tcp_header *th = dp_packet_l4(packet);
1072
1073     packet_set_port(&th->tcp_src, src, &th->tcp_csum);
1074     packet_set_port(&th->tcp_dst, dst, &th->tcp_csum);
1075 }
1076
1077 /* Sets the UDP source and destination port ('src' and 'dst' respectively) of
1078  * the UDP header contained in 'packet'.  'packet' must be a valid UDP packet
1079  * with its l4 offset properly populated. */
1080 void
1081 packet_set_udp_port(struct dp_packet *packet, ovs_be16 src, ovs_be16 dst)
1082 {
1083     struct udp_header *uh = dp_packet_l4(packet);
1084
1085     if (uh->udp_csum) {
1086         packet_set_port(&uh->udp_src, src, &uh->udp_csum);
1087         packet_set_port(&uh->udp_dst, dst, &uh->udp_csum);
1088
1089         if (!uh->udp_csum) {
1090             uh->udp_csum = htons(0xffff);
1091         }
1092     } else {
1093         uh->udp_src = src;
1094         uh->udp_dst = dst;
1095     }
1096 }
1097
1098 /* Sets the SCTP source and destination port ('src' and 'dst' respectively) of
1099  * the SCTP header contained in 'packet'.  'packet' must be a valid SCTP packet
1100  * with its l4 offset properly populated. */
1101 void
1102 packet_set_sctp_port(struct dp_packet *packet, ovs_be16 src, ovs_be16 dst)
1103 {
1104     struct sctp_header *sh = dp_packet_l4(packet);
1105     ovs_be32 old_csum, old_correct_csum, new_csum;
1106     uint16_t tp_len = dp_packet_l4_size(packet);
1107
1108     old_csum = get_16aligned_be32(&sh->sctp_csum);
1109     put_16aligned_be32(&sh->sctp_csum, 0);
1110     old_correct_csum = crc32c((void *)sh, tp_len);
1111
1112     sh->sctp_src = src;
1113     sh->sctp_dst = dst;
1114
1115     new_csum = crc32c((void *)sh, tp_len);
1116     put_16aligned_be32(&sh->sctp_csum, old_csum ^ old_correct_csum ^ new_csum);
1117 }
1118
1119 /* Sets the ICMP type and code of the ICMP header contained in 'packet'.
1120  * 'packet' must be a valid ICMP packet with its l4 offset properly
1121  * populated. */
1122 void
1123 packet_set_icmp(struct dp_packet *packet, uint8_t type, uint8_t code)
1124 {
1125     struct icmp_header *ih = dp_packet_l4(packet);
1126     ovs_be16 orig_tc = htons(ih->icmp_type << 8 | ih->icmp_code);
1127     ovs_be16 new_tc = htons(type << 8 | code);
1128
1129     if (orig_tc != new_tc) {
1130         ih->icmp_type = type;
1131         ih->icmp_code = code;
1132
1133         ih->icmp_csum = recalc_csum16(ih->icmp_csum, orig_tc, new_tc);
1134     }
1135 }
1136
1137 void
1138 packet_set_nd(struct dp_packet *packet, const ovs_be32 target[4],
1139               const struct eth_addr sll, const struct eth_addr tll)
1140 {
1141     struct ovs_nd_msg *ns;
1142     struct ovs_nd_opt *nd_opt;
1143     int bytes_remain = dp_packet_l4_size(packet);
1144
1145     if (OVS_UNLIKELY(bytes_remain < sizeof(*ns))) {
1146         return;
1147     }
1148
1149     ns = dp_packet_l4(packet);
1150     nd_opt = &ns->options[0];
1151     bytes_remain -= sizeof(*ns);
1152
1153     if (memcmp(&ns->target, target, sizeof(ovs_be32[4]))) {
1154         packet_set_ipv6_addr(packet, IPPROTO_ICMPV6,
1155                              ns->target.be32,
1156                              target, true);
1157     }
1158
1159     while (bytes_remain >= ND_OPT_LEN && nd_opt->nd_opt_len != 0) {
1160         if (nd_opt->nd_opt_type == ND_OPT_SOURCE_LINKADDR
1161             && nd_opt->nd_opt_len == 1) {
1162             if (!eth_addr_equals(nd_opt->nd_opt_mac, sll)) {
1163                 ovs_be16 *csum = &(ns->icmph.icmp6_cksum);
1164
1165                 *csum = recalc_csum48(*csum, nd_opt->nd_opt_mac, sll);
1166                 nd_opt->nd_opt_mac = sll;
1167             }
1168
1169             /* A packet can only contain one SLL or TLL option */
1170             break;
1171         } else if (nd_opt->nd_opt_type == ND_OPT_TARGET_LINKADDR
1172                    && nd_opt->nd_opt_len == 1) {
1173             if (!eth_addr_equals(nd_opt->nd_opt_mac, tll)) {
1174                 ovs_be16 *csum = &(ns->icmph.icmp6_cksum);
1175
1176                 *csum = recalc_csum48(*csum, nd_opt->nd_opt_mac, tll);
1177                 nd_opt->nd_opt_mac = tll;
1178             }
1179
1180             /* A packet can only contain one SLL or TLL option */
1181             break;
1182         }
1183
1184         nd_opt += nd_opt->nd_opt_len;
1185         bytes_remain -= nd_opt->nd_opt_len * ND_OPT_LEN;
1186     }
1187 }
1188
1189 const char *
1190 packet_tcp_flag_to_string(uint32_t flag)
1191 {
1192     switch (flag) {
1193     case TCP_FIN:
1194         return "fin";
1195     case TCP_SYN:
1196         return "syn";
1197     case TCP_RST:
1198         return "rst";
1199     case TCP_PSH:
1200         return "psh";
1201     case TCP_ACK:
1202         return "ack";
1203     case TCP_URG:
1204         return "urg";
1205     case TCP_ECE:
1206         return "ece";
1207     case TCP_CWR:
1208         return "cwr";
1209     case TCP_NS:
1210         return "ns";
1211     case 0x200:
1212         return "[200]";
1213     case 0x400:
1214         return "[400]";
1215     case 0x800:
1216         return "[800]";
1217     default:
1218         return NULL;
1219     }
1220 }
1221
1222 /* Appends a string representation of the TCP flags value 'tcp_flags'
1223  * (e.g. from struct flow.tcp_flags or obtained via TCP_FLAGS) to 's', in the
1224  * format used by tcpdump. */
1225 void
1226 packet_format_tcp_flags(struct ds *s, uint16_t tcp_flags)
1227 {
1228     if (!tcp_flags) {
1229         ds_put_cstr(s, "none");
1230         return;
1231     }
1232
1233     if (tcp_flags & TCP_SYN) {
1234         ds_put_char(s, 'S');
1235     }
1236     if (tcp_flags & TCP_FIN) {
1237         ds_put_char(s, 'F');
1238     }
1239     if (tcp_flags & TCP_PSH) {
1240         ds_put_char(s, 'P');
1241     }
1242     if (tcp_flags & TCP_RST) {
1243         ds_put_char(s, 'R');
1244     }
1245     if (tcp_flags & TCP_URG) {
1246         ds_put_char(s, 'U');
1247     }
1248     if (tcp_flags & TCP_ACK) {
1249         ds_put_char(s, '.');
1250     }
1251     if (tcp_flags & TCP_ECE) {
1252         ds_put_cstr(s, "E");
1253     }
1254     if (tcp_flags & TCP_CWR) {
1255         ds_put_cstr(s, "C");
1256     }
1257     if (tcp_flags & TCP_NS) {
1258         ds_put_cstr(s, "N");
1259     }
1260     if (tcp_flags & 0x200) {
1261         ds_put_cstr(s, "[200]");
1262     }
1263     if (tcp_flags & 0x400) {
1264         ds_put_cstr(s, "[400]");
1265     }
1266     if (tcp_flags & 0x800) {
1267         ds_put_cstr(s, "[800]");
1268     }
1269 }
1270
1271 #define ARP_PACKET_SIZE  (2 + ETH_HEADER_LEN + VLAN_HEADER_LEN + \
1272                           ARP_ETH_HEADER_LEN)
1273
1274 /* Clears 'b' and replaces its contents by an ARP frame with the specified
1275  * 'arp_op', 'arp_sha', 'arp_tha', 'arp_spa', and 'arp_tpa'.  The outer
1276  * Ethernet frame is initialized with Ethernet source 'arp_sha' and destination
1277  * 'arp_tha', except that destination ff:ff:ff:ff:ff:ff is used instead if
1278  * 'broadcast' is true.  Points the L3 header to the ARP header. */
1279 void
1280 compose_arp(struct dp_packet *b, uint16_t arp_op,
1281             const struct eth_addr arp_sha, const struct eth_addr arp_tha,
1282             bool broadcast, ovs_be32 arp_spa, ovs_be32 arp_tpa)
1283 {
1284     compose_arp__(b);
1285
1286     struct eth_header *eth = dp_packet_l2(b);
1287     eth->eth_dst = broadcast ? eth_addr_broadcast : arp_tha;
1288     eth->eth_src = arp_sha;
1289
1290     struct arp_eth_header *arp = dp_packet_l3(b);
1291     arp->ar_op = htons(arp_op);
1292     arp->ar_sha = arp_sha;
1293     arp->ar_tha = arp_tha;
1294     put_16aligned_be32(&arp->ar_spa, arp_spa);
1295     put_16aligned_be32(&arp->ar_tpa, arp_tpa);
1296 }
1297
1298 /* Clears 'b' and replaces its contents by an ARP frame.  Sets the fields in
1299  * the Ethernet and ARP headers that are fixed for ARP frames to those fixed
1300  * values, and zeroes the other fields.  Points the L3 header to the ARP
1301  * header. */
1302 void
1303 compose_arp__(struct dp_packet *b)
1304 {
1305     dp_packet_clear(b);
1306     dp_packet_prealloc_tailroom(b, ARP_PACKET_SIZE);
1307     dp_packet_reserve(b, 2 + VLAN_HEADER_LEN);
1308
1309     struct eth_header *eth = dp_packet_put_zeros(b, sizeof *eth);
1310     eth->eth_type = htons(ETH_TYPE_ARP);
1311
1312     struct arp_eth_header *arp = dp_packet_put_zeros(b, sizeof *arp);
1313     arp->ar_hrd = htons(ARP_HRD_ETHERNET);
1314     arp->ar_pro = htons(ARP_PRO_IP);
1315     arp->ar_hln = sizeof arp->ar_sha;
1316     arp->ar_pln = sizeof arp->ar_spa;
1317
1318     dp_packet_reset_offsets(b);
1319     dp_packet_set_l3(b, arp);
1320 }
1321
1322 /* This function expect packet with ethernet header with correct
1323  * l3 pointer set. */
1324 static void *
1325 compose_ipv6(struct dp_packet *packet, uint8_t proto, const ovs_be32 src[4],
1326              const ovs_be32 dst[4], uint8_t key_tc, ovs_be32 key_fl,
1327              uint8_t key_hl, int size)
1328 {
1329     struct ip6_hdr *nh;
1330     void *data;
1331
1332     nh = dp_packet_l3(packet);
1333     nh->ip6_vfc = 0x60;
1334     nh->ip6_nxt = proto;
1335     nh->ip6_plen = htons(size);
1336     data = dp_packet_put_zeros(packet, size);
1337     dp_packet_set_l4(packet, data);
1338     packet_set_ipv6(packet, src, dst, key_tc, key_fl, key_hl);
1339     return data;
1340 }
1341
1342 void
1343 compose_nd(struct dp_packet *b, const struct eth_addr eth_src,
1344            struct in6_addr *ipv6_src, struct in6_addr *ipv6_dst)
1345 {
1346     struct in6_addr sn_addr;
1347     struct eth_addr eth_dst;
1348     struct ovs_nd_msg *ns;
1349     struct ovs_nd_opt *nd_opt;
1350     uint32_t icmp_csum;
1351
1352     in6_addr_solicited_node(&sn_addr, ipv6_dst);
1353     ipv6_multicast_to_ethernet(&eth_dst, &sn_addr);
1354
1355     eth_compose(b, eth_dst, eth_src, ETH_TYPE_IPV6, IPV6_HEADER_LEN);
1356     ns = compose_ipv6(b, IPPROTO_ICMPV6,
1357                       ALIGNED_CAST(ovs_be32 *, ipv6_src->s6_addr),
1358                       ALIGNED_CAST(ovs_be32 *, sn_addr.s6_addr),
1359                       0, 0, 255,
1360                       ND_MSG_LEN + ND_OPT_LEN);
1361
1362     ns->icmph.icmp6_type = ND_NEIGHBOR_SOLICIT;
1363     ns->icmph.icmp6_code = 0;
1364     put_16aligned_be32(&ns->rso_flags, htonl(0));
1365
1366     nd_opt = &ns->options[0];
1367     nd_opt->nd_opt_type = ND_OPT_SOURCE_LINKADDR;
1368     nd_opt->nd_opt_len = 1;
1369
1370     packet_set_nd(b, ALIGNED_CAST(ovs_be32 *, ipv6_dst->s6_addr),
1371                   eth_src, eth_addr_zero);
1372     ns->icmph.icmp6_cksum = 0;
1373     icmp_csum = packet_csum_pseudoheader6(dp_packet_l3(b));
1374     ns->icmph.icmp6_cksum = csum_finish(csum_continue(icmp_csum, ns,
1375                                                       ND_MSG_LEN + ND_OPT_LEN));
1376 }
1377
1378 void
1379 compose_na(struct dp_packet *b,
1380            const struct eth_addr eth_src, const struct eth_addr eth_dst,
1381            const ovs_be32 ipv6_src[4], const ovs_be32 ipv6_dst[4],
1382            ovs_be32 rso_flags)
1383 {
1384     struct ovs_nd_msg *na;
1385     struct ovs_nd_opt *nd_opt;
1386     uint32_t icmp_csum;
1387
1388     eth_compose(b, eth_dst, eth_src, ETH_TYPE_IPV6, IPV6_HEADER_LEN);
1389     na = compose_ipv6(b, IPPROTO_ICMPV6, ipv6_src, ipv6_dst, 0, 0, 255,
1390                       ND_MSG_LEN + ND_OPT_LEN);
1391
1392     na->icmph.icmp6_type = ND_NEIGHBOR_ADVERT;
1393     na->icmph.icmp6_code = 0;
1394     put_16aligned_be32(&na->rso_flags, rso_flags);
1395
1396     nd_opt = &na->options[0];
1397     nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
1398     nd_opt->nd_opt_len = 1;
1399
1400     packet_set_nd(b, ipv6_src, eth_addr_zero, eth_src);
1401     na->icmph.icmp6_cksum = 0;
1402     icmp_csum = packet_csum_pseudoheader6(dp_packet_l3(b));
1403     na->icmph.icmp6_cksum = csum_finish(csum_continue(icmp_csum, na,
1404                                                       ND_MSG_LEN + ND_OPT_LEN));
1405 }
1406
1407 uint32_t
1408 packet_csum_pseudoheader(const struct ip_header *ip)
1409 {
1410     uint32_t partial = 0;
1411
1412     partial = csum_add32(partial, get_16aligned_be32(&ip->ip_src));
1413     partial = csum_add32(partial, get_16aligned_be32(&ip->ip_dst));
1414     partial = csum_add16(partial, htons(ip->ip_proto));
1415     partial = csum_add16(partial, htons(ntohs(ip->ip_tot_len) -
1416                                         IP_IHL(ip->ip_ihl_ver) * 4));
1417
1418     return partial;
1419 }
1420
1421 #ifndef __CHECKER__
1422 uint32_t
1423 packet_csum_pseudoheader6(const struct ovs_16aligned_ip6_hdr *ip6)
1424 {
1425     uint32_t partial = 0;
1426
1427     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_src.be32[0])));
1428     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_src.be32[1])));
1429     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_src.be32[2])));
1430     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_src.be32[3])));
1431
1432     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_dst.be32[0])));
1433     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_dst.be32[1])));
1434     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_dst.be32[2])));
1435     partial = csum_add32(partial, get_16aligned_be32(&(ip6->ip6_dst.be32[3])));
1436
1437     partial = csum_add16(partial, htons(ip6->ip6_nxt));
1438     partial = csum_add16(partial, ip6->ip6_plen);
1439
1440     return partial;
1441 }
1442 #endif
1443
1444 void
1445 IP_ECN_set_ce(struct dp_packet *pkt, bool is_ipv6)
1446 {
1447     if (is_ipv6) {
1448         ovs_16aligned_be32 *ip6 = dp_packet_l3(pkt);
1449
1450         put_16aligned_be32(ip6, get_16aligned_be32(ip6) |
1451                                 htonl(IP_ECN_CE << 20));
1452     } else {
1453         struct ip_header *nh = dp_packet_l3(pkt);
1454         uint8_t tos = nh->ip_tos;
1455
1456         tos |= IP_ECN_CE;
1457         if (nh->ip_tos != tos) {
1458             nh->ip_csum = recalc_csum16(nh->ip_csum, htons(nh->ip_tos),
1459                                         htons((uint16_t) tos));
1460             nh->ip_tos = tos;
1461         }
1462     }
1463 }