d87aa8eb34019f9ed00cf9c4b9fc47baded420fe
[cascardo/ovs.git] / lib / packets.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 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 <stdlib.h>
24 #include "byte-order.h"
25 #include "csum.h"
26 #include "crc32c.h"
27 #include "flow.h"
28 #include "hmap.h"
29 #include "dynamic-string.h"
30 #include "ofpbuf.h"
31 #include "ovs-thread.h"
32 #include "unaligned.h"
33
34 const struct in6_addr in6addr_exact = IN6ADDR_EXACT_INIT;
35
36 /* Parses 's' as a 16-digit hexadecimal number representing a datapath ID.  On
37  * success stores the dpid into '*dpidp' and returns true, on failure stores 0
38  * into '*dpidp' and returns false.
39  *
40  * Rejects an all-zeros dpid as invalid. */
41 bool
42 dpid_from_string(const char *s, uint64_t *dpidp)
43 {
44     *dpidp = (strlen(s) == 16 && strspn(s, "0123456789abcdefABCDEF") == 16
45               ? strtoull(s, NULL, 16)
46               : 0);
47     return *dpidp != 0;
48 }
49
50 /* Returns true if 'ea' is a reserved address, that a bridge must never
51  * forward, false otherwise.
52  *
53  * If you change this function's behavior, please update corresponding
54  * documentation in vswitch.xml at the same time. */
55 bool
56 eth_addr_is_reserved(const uint8_t ea[ETH_ADDR_LEN])
57 {
58     struct eth_addr_node {
59         struct hmap_node hmap_node;
60         const uint64_t ea64;
61     };
62
63     static struct eth_addr_node nodes[] = {
64         /* STP, IEEE pause frames, and other reserved protocols. */
65         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000000ULL },
66         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000001ULL },
67         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000002ULL },
68         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000003ULL },
69         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000004ULL },
70         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000005ULL },
71         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000006ULL },
72         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000007ULL },
73         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000008ULL },
74         { HMAP_NODE_NULL_INITIALIZER, 0x0180c2000009ULL },
75         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000aULL },
76         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000bULL },
77         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000cULL },
78         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000dULL },
79         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000eULL },
80         { HMAP_NODE_NULL_INITIALIZER, 0x0180c200000fULL },
81
82         /* Extreme protocols. */
83         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000000ULL }, /* EDP. */
84         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000004ULL }, /* EAPS. */
85         { HMAP_NODE_NULL_INITIALIZER, 0x00e02b000006ULL }, /* EAPS. */
86
87         /* Cisco protocols. */
88         { HMAP_NODE_NULL_INITIALIZER, 0x01000c000000ULL }, /* ISL. */
89         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccccULL }, /* PAgP, UDLD, CDP,
90                                                             * DTP, VTP. */
91         { HMAP_NODE_NULL_INITIALIZER, 0x01000ccccccdULL }, /* PVST+. */
92         { HMAP_NODE_NULL_INITIALIZER, 0x01000ccdcdcdULL }, /* STP Uplink Fast,
93                                                             * FlexLink. */
94
95         /* Cisco CFM. */
96         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc0ULL },
97         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc1ULL },
98         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc2ULL },
99         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc3ULL },
100         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc4ULL },
101         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc5ULL },
102         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc6ULL },
103         { HMAP_NODE_NULL_INITIALIZER, 0x01000cccccc7ULL },
104     };
105
106     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
107     struct eth_addr_node *node;
108     static struct hmap addrs;
109     uint64_t ea64;
110
111     if (ovsthread_once_start(&once)) {
112         hmap_init(&addrs);
113         for (node = nodes; node < &nodes[ARRAY_SIZE(nodes)]; node++) {
114             hmap_insert(&addrs, &node->hmap_node,
115                         hash_2words(node->ea64, node->ea64 >> 32));
116         }
117         ovsthread_once_done(&once);
118     }
119
120     ea64 = eth_addr_to_uint64(ea);
121     HMAP_FOR_EACH_IN_BUCKET (node, hmap_node, hash_2words(ea64, ea64 >> 32),
122                              &addrs) {
123         if (node->ea64 == ea64) {
124             return true;
125         }
126     }
127     return false;
128 }
129
130 bool
131 eth_addr_from_string(const char *s, uint8_t ea[ETH_ADDR_LEN])
132 {
133     if (ovs_scan(s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(ea))) {
134         return true;
135     } else {
136         memset(ea, 0, ETH_ADDR_LEN);
137         return false;
138     }
139 }
140
141 /* Fills 'b' with a Reverse ARP packet with Ethernet source address 'eth_src'.
142  * This function is used by Open vSwitch to compose packets in cases where
143  * context is important but content doesn't (or shouldn't) matter.
144  *
145  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
146  * desired. */
147 void
148 compose_rarp(struct ofpbuf *b, const uint8_t eth_src[ETH_ADDR_LEN])
149 {
150     struct eth_header *eth;
151     struct arp_eth_header *arp;
152
153     ofpbuf_clear(b);
154     ofpbuf_prealloc_tailroom(b, 2 + ETH_HEADER_LEN + VLAN_HEADER_LEN
155                              + ARP_ETH_HEADER_LEN);
156     ofpbuf_reserve(b, 2 + VLAN_HEADER_LEN);
157     eth = ofpbuf_put_uninit(b, sizeof *eth);
158     memcpy(eth->eth_dst, eth_addr_broadcast, ETH_ADDR_LEN);
159     memcpy(eth->eth_src, eth_src, ETH_ADDR_LEN);
160     eth->eth_type = htons(ETH_TYPE_RARP);
161
162     arp = ofpbuf_put_uninit(b, sizeof *arp);
163     arp->ar_hrd = htons(ARP_HRD_ETHERNET);
164     arp->ar_pro = htons(ARP_PRO_IP);
165     arp->ar_hln = sizeof arp->ar_sha;
166     arp->ar_pln = sizeof arp->ar_spa;
167     arp->ar_op = htons(ARP_OP_RARP);
168     memcpy(arp->ar_sha, eth_src, ETH_ADDR_LEN);
169     put_16aligned_be32(&arp->ar_spa, htonl(0));
170     memcpy(arp->ar_tha, eth_src, ETH_ADDR_LEN);
171     put_16aligned_be32(&arp->ar_tpa, htonl(0));
172 }
173
174 /* Insert VLAN header according to given TCI. Packet passed must be Ethernet
175  * packet.  Ignores the CFI bit of 'tci' using 0 instead.
176  *
177  * Also sets 'packet->l2' to point to the new Ethernet header. */
178 void
179 eth_push_vlan(struct ofpbuf *packet, ovs_be16 tci)
180 {
181     struct eth_header *eh = packet->data;
182     struct vlan_eth_header *veh;
183
184     /* Insert new 802.1Q header. */
185     struct vlan_eth_header tmp;
186     memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
187     memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
188     tmp.veth_type = htons(ETH_TYPE_VLAN);
189     tmp.veth_tci = tci & htons(~VLAN_CFI);
190     tmp.veth_next_type = eh->eth_type;
191
192     veh = ofpbuf_push_uninit(packet, VLAN_HEADER_LEN);
193     memcpy(veh, &tmp, sizeof tmp);
194
195     packet->l2 = packet->data;
196 }
197
198 /* Removes outermost VLAN header (if any is present) from 'packet'.
199  *
200  * 'packet->l2_5' should initially point to 'packet''s outer-most MPLS header
201  * or may be NULL if there are no MPLS headers. */
202 void
203 eth_pop_vlan(struct ofpbuf *packet)
204 {
205     struct vlan_eth_header *veh = packet->l2;
206     if (packet->size >= sizeof *veh
207         && veh->veth_type == htons(ETH_TYPE_VLAN)) {
208         struct eth_header tmp;
209
210         memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
211         memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
212         tmp.eth_type = veh->veth_next_type;
213
214         ofpbuf_pull(packet, VLAN_HEADER_LEN);
215         packet->l2 = (char*)packet->l2 + VLAN_HEADER_LEN;
216         memcpy(packet->data, &tmp, sizeof tmp);
217     }
218 }
219
220 /* Set ethertype of the packet. */
221 void
222 set_ethertype(struct ofpbuf *packet, ovs_be16 eth_type)
223 {
224     struct eth_header *eh = packet->data;
225
226     if (eh->eth_type == htons(ETH_TYPE_VLAN)) {
227         ovs_be16 *p;
228         p = ALIGNED_CAST(ovs_be16 *,
229                 (char *)(packet->l2_5 ? packet->l2_5 : packet->l3) - 2);
230         *p = eth_type;
231     } else {
232         eh->eth_type = eth_type;
233     }
234 }
235
236 static bool is_mpls(struct ofpbuf *packet)
237 {
238     return packet->l2_5 != NULL;
239 }
240
241 /* Set time to live (TTL) of an MPLS label stack entry (LSE). */
242 void
243 set_mpls_lse_ttl(ovs_be32 *lse, uint8_t ttl)
244 {
245     *lse &= ~htonl(MPLS_TTL_MASK);
246     *lse |= htonl((ttl << MPLS_TTL_SHIFT) & MPLS_TTL_MASK);
247 }
248
249 /* Set traffic class (TC) of an MPLS label stack entry (LSE). */
250 void
251 set_mpls_lse_tc(ovs_be32 *lse, uint8_t tc)
252 {
253     *lse &= ~htonl(MPLS_TC_MASK);
254     *lse |= htonl((tc << MPLS_TC_SHIFT) & MPLS_TC_MASK);
255 }
256
257 /* Set label of an MPLS label stack entry (LSE). */
258 void
259 set_mpls_lse_label(ovs_be32 *lse, ovs_be32 label)
260 {
261     *lse &= ~htonl(MPLS_LABEL_MASK);
262     *lse |= htonl((ntohl(label) << MPLS_LABEL_SHIFT) & MPLS_LABEL_MASK);
263 }
264
265 /* Set bottom of stack (BoS) bit of an MPLS label stack entry (LSE). */
266 void
267 set_mpls_lse_bos(ovs_be32 *lse, uint8_t bos)
268 {
269     *lse &= ~htonl(MPLS_BOS_MASK);
270     *lse |= htonl((bos << MPLS_BOS_SHIFT) & MPLS_BOS_MASK);
271 }
272
273 /* Compose an MPLS label stack entry (LSE) from its components:
274  * label, traffic class (TC), time to live (TTL) and
275  * bottom of stack (BoS) bit. */
276 ovs_be32
277 set_mpls_lse_values(uint8_t ttl, uint8_t tc, uint8_t bos, ovs_be32 label)
278 {
279     ovs_be32 lse = htonl(0);
280     set_mpls_lse_ttl(&lse, ttl);
281     set_mpls_lse_tc(&lse, tc);
282     set_mpls_lse_bos(&lse, bos);
283     set_mpls_lse_label(&lse, label);
284     return lse;
285 }
286
287 /* Push an new MPLS stack entry onto the MPLS stack and adjust 'packet->l2' and
288  * 'packet->l2_5' accordingly.  The new entry will be the outermost entry on
289  * the stack.
290  *
291  * Previous to calling this function, 'packet->l2_5' must be set; if the MPLS
292  * label to be pushed will be the first label in 'packet', then it should be
293  * the same as 'packet->l3'. */
294 static void
295 push_mpls_lse(struct ofpbuf *packet, struct mpls_hdr *mh)
296 {
297     char * header;
298     size_t len;
299     header = ofpbuf_push_uninit(packet, MPLS_HLEN);
300     len = (char *)packet->l2_5 - (char *)packet->l2;
301     memmove(header, packet->l2, len);
302     memcpy(header + len, mh, sizeof *mh);
303     packet->l2 = (char*)packet->l2 - MPLS_HLEN;
304     packet->l2_5 = (char*)packet->l2_5 - MPLS_HLEN;
305 }
306
307 /* Set MPLS label stack entry to outermost MPLS header.*/
308 void
309 set_mpls_lse(struct ofpbuf *packet, ovs_be32 mpls_lse)
310 {
311     struct mpls_hdr *mh = packet->l2_5;
312
313     /* Packet type should be MPLS to set label stack entry. */
314     if (is_mpls(packet)) {
315         /* Update mpls label stack entry. */
316         mh->mpls_lse = mpls_lse;
317     }
318 }
319
320 /* Push MPLS label stack entry 'lse' onto 'packet' as the the outermost MPLS
321  * header.  If 'packet' does not already have any MPLS labels, then its
322  * Ethertype is changed to 'ethtype' (which must be an MPLS Ethertype). */
323 void
324 push_mpls(struct ofpbuf *packet, ovs_be16 ethtype, ovs_be32 lse)
325 {
326     struct mpls_hdr mh;
327
328     if (!eth_type_mpls(ethtype)) {
329         return;
330     }
331
332     if (!is_mpls(packet)) {
333         /* Set ethtype and MPLS label stack entry. */
334         set_ethertype(packet, ethtype);
335         packet->l2_5 = packet->l3;
336     }
337
338     /* Push new MPLS shim header onto packet. */
339     mh.mpls_lse = lse;
340     push_mpls_lse(packet, &mh);
341 }
342
343 /* If 'packet' is an MPLS packet, removes its outermost MPLS label stack entry.
344  * If the label that was removed was the only MPLS label, changes 'packet''s
345  * Ethertype to 'ethtype' (which ordinarily should not be an MPLS
346  * Ethertype). */
347 void
348 pop_mpls(struct ofpbuf *packet, ovs_be16 ethtype)
349 {
350     struct mpls_hdr *mh = NULL;
351
352     if (is_mpls(packet)) {
353         size_t len;
354         mh = packet->l2_5;
355         len = (char*)packet->l2_5 - (char*)packet->l2;
356         set_ethertype(packet, ethtype);
357         if (mh->mpls_lse & htonl(MPLS_BOS_MASK)) {
358             packet->l2_5 = NULL;
359         } else {
360             packet->l2_5 = (char*)packet->l2_5 + MPLS_HLEN;
361         }
362         /* Shift the l2 header forward. */
363         memmove((char*)packet->data + MPLS_HLEN, packet->data, len);
364         packet->size -= MPLS_HLEN;
365         packet->data = (char*)packet->data + MPLS_HLEN;
366         packet->l2 = (char*)packet->l2 + MPLS_HLEN;
367     }
368 }
369
370 /* Converts hex digits in 'hex' to an Ethernet packet in '*packetp'.  The
371  * caller must free '*packetp'.  On success, returns NULL.  On failure, returns
372  * an error message and stores NULL in '*packetp'.
373  *
374  * Aligns the L3 header of '*packetp' on a 32-bit boundary. */
375 const char *
376 eth_from_hex(const char *hex, struct ofpbuf **packetp)
377 {
378     struct ofpbuf *packet;
379
380     /* Use 2 bytes of headroom to 32-bit align the L3 header. */
381     packet = *packetp = ofpbuf_new_with_headroom(strlen(hex) / 2, 2);
382
383     if (ofpbuf_put_hex(packet, hex, NULL)[0] != '\0') {
384         ofpbuf_delete(packet);
385         *packetp = NULL;
386         return "Trailing garbage in packet data";
387     }
388
389     if (packet->size < ETH_HEADER_LEN) {
390         ofpbuf_delete(packet);
391         *packetp = NULL;
392         return "Packet data too short for Ethernet";
393     }
394
395     return NULL;
396 }
397
398 void
399 eth_format_masked(const uint8_t eth[ETH_ADDR_LEN],
400                   const uint8_t mask[ETH_ADDR_LEN], struct ds *s)
401 {
402     ds_put_format(s, ETH_ADDR_FMT, ETH_ADDR_ARGS(eth));
403     if (mask && !eth_mask_is_exact(mask)) {
404         ds_put_format(s, "/"ETH_ADDR_FMT, ETH_ADDR_ARGS(mask));
405     }
406 }
407
408 void
409 eth_addr_bitand(const uint8_t src[ETH_ADDR_LEN],
410                 const uint8_t mask[ETH_ADDR_LEN],
411                 uint8_t dst[ETH_ADDR_LEN])
412 {
413     int i;
414
415     for (i = 0; i < ETH_ADDR_LEN; i++) {
416         dst[i] = src[i] & mask[i];
417     }
418 }
419
420 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
421  * that it specifies, that is, the number of 1-bits in 'netmask'.
422  *
423  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
424  * still be in the valid range but isn't otherwise meaningful. */
425 int
426 ip_count_cidr_bits(ovs_be32 netmask)
427 {
428     return 32 - ctz32(ntohl(netmask));
429 }
430
431 void
432 ip_format_masked(ovs_be32 ip, ovs_be32 mask, struct ds *s)
433 {
434     ds_put_format(s, IP_FMT, IP_ARGS(ip));
435     if (mask != OVS_BE32_MAX) {
436         if (ip_is_cidr(mask)) {
437             ds_put_format(s, "/%d", ip_count_cidr_bits(mask));
438         } else {
439             ds_put_format(s, "/"IP_FMT, IP_ARGS(mask));
440         }
441     }
442 }
443
444
445 /* Stores the string representation of the IPv6 address 'addr' into the
446  * character array 'addr_str', which must be at least INET6_ADDRSTRLEN
447  * bytes long. */
448 void
449 format_ipv6_addr(char *addr_str, const struct in6_addr *addr)
450 {
451     inet_ntop(AF_INET6, addr, addr_str, INET6_ADDRSTRLEN);
452 }
453
454 void
455 print_ipv6_addr(struct ds *string, const struct in6_addr *addr)
456 {
457     char *dst;
458
459     ds_reserve(string, string->length + INET6_ADDRSTRLEN);
460
461     dst = string->string + string->length;
462     format_ipv6_addr(dst, addr);
463     string->length += strlen(dst);
464 }
465
466 void
467 print_ipv6_masked(struct ds *s, const struct in6_addr *addr,
468                   const struct in6_addr *mask)
469 {
470     print_ipv6_addr(s, addr);
471     if (mask && !ipv6_mask_is_exact(mask)) {
472         if (ipv6_is_cidr(mask)) {
473             int cidr_bits = ipv6_count_cidr_bits(mask);
474             ds_put_format(s, "/%d", cidr_bits);
475         } else {
476             ds_put_char(s, '/');
477             print_ipv6_addr(s, mask);
478         }
479     }
480 }
481
482 struct in6_addr ipv6_addr_bitand(const struct in6_addr *a,
483                                  const struct in6_addr *b)
484 {
485     int i;
486     struct in6_addr dst;
487
488 #ifdef s6_addr32
489     for (i=0; i<4; i++) {
490         dst.s6_addr32[i] = a->s6_addr32[i] & b->s6_addr32[i];
491     }
492 #else
493     for (i=0; i<16; i++) {
494         dst.s6_addr[i] = a->s6_addr[i] & b->s6_addr[i];
495     }
496 #endif
497
498     return dst;
499 }
500
501 /* Returns an in6_addr consisting of 'mask' high-order 1-bits and 128-N
502  * low-order 0-bits. */
503 struct in6_addr
504 ipv6_create_mask(int mask)
505 {
506     struct in6_addr netmask;
507     uint8_t *netmaskp = &netmask.s6_addr[0];
508
509     memset(&netmask, 0, sizeof netmask);
510     while (mask > 8) {
511         *netmaskp = 0xff;
512         netmaskp++;
513         mask -= 8;
514     }
515
516     if (mask) {
517         *netmaskp = 0xff << (8 - mask);
518     }
519
520     return netmask;
521 }
522
523 /* Given the IPv6 netmask 'netmask', returns the number of bits of the IPv6
524  * address that it specifies, that is, the number of 1-bits in 'netmask'.
525  * 'netmask' must be a CIDR netmask (see ipv6_is_cidr()).
526  *
527  * If 'netmask' is not a CIDR netmask (see ipv6_is_cidr()), the return value
528  * will still be in the valid range but isn't otherwise meaningful. */
529 int
530 ipv6_count_cidr_bits(const struct in6_addr *netmask)
531 {
532     int i;
533     int count = 0;
534     const uint8_t *netmaskp = &netmask->s6_addr[0];
535
536     for (i=0; i<16; i++) {
537         if (netmaskp[i] == 0xff) {
538             count += 8;
539         } else {
540             uint8_t nm;
541
542             for(nm = netmaskp[i]; nm; nm <<= 1) {
543                 count++;
544             }
545             break;
546         }
547
548     }
549
550     return count;
551 }
552
553 /* Returns true if 'netmask' is a CIDR netmask, that is, if it consists of N
554  * high-order 1-bits and 128-N low-order 0-bits. */
555 bool
556 ipv6_is_cidr(const struct in6_addr *netmask)
557 {
558     const uint8_t *netmaskp = &netmask->s6_addr[0];
559     int i;
560
561     for (i=0; i<16; i++) {
562         if (netmaskp[i] != 0xff) {
563             uint8_t x = ~netmaskp[i];
564             if (x & (x + 1)) {
565                 return false;
566             }
567             while (++i < 16) {
568                 if (netmaskp[i]) {
569                     return false;
570                 }
571             }
572         }
573     }
574
575     return true;
576 }
577
578 /* Populates 'b' with an Ethernet II packet headed with the given 'eth_dst',
579  * 'eth_src' and 'eth_type' parameters.  A payload of 'size' bytes is allocated
580  * in 'b' and returned.  This payload may be populated with appropriate
581  * information by the caller.  Sets 'b''s 'l2' and 'l3' pointers to the
582  * Ethernet header and payload respectively.  Aligns b->l3 on a 32-bit
583  * boundary.
584  *
585  * The returned packet has enough headroom to insert an 802.1Q VLAN header if
586  * desired. */
587 void *
588 eth_compose(struct ofpbuf *b, const uint8_t eth_dst[ETH_ADDR_LEN],
589             const uint8_t eth_src[ETH_ADDR_LEN], uint16_t eth_type,
590             size_t size)
591 {
592     void *data;
593     struct eth_header *eth;
594
595     ofpbuf_clear(b);
596
597     /* The magic 2 here ensures that the L3 header (when it is added later)
598      * will be 32-bit aligned. */
599     ofpbuf_prealloc_tailroom(b, 2 + ETH_HEADER_LEN + VLAN_HEADER_LEN + size);
600     ofpbuf_reserve(b, 2 + VLAN_HEADER_LEN);
601     eth = ofpbuf_put_uninit(b, ETH_HEADER_LEN);
602     data = ofpbuf_put_uninit(b, size);
603
604     memcpy(eth->eth_dst, eth_dst, ETH_ADDR_LEN);
605     memcpy(eth->eth_src, eth_src, ETH_ADDR_LEN);
606     eth->eth_type = htons(eth_type);
607
608     b->l2 = eth;
609     b->l3 = data;
610
611     return data;
612 }
613
614 static void
615 packet_set_ipv4_addr(struct ofpbuf *packet,
616                      ovs_16aligned_be32 *addr, ovs_be32 new_addr)
617 {
618     struct ip_header *nh = packet->l3;
619     ovs_be32 old_addr = get_16aligned_be32(addr);
620
621     if (nh->ip_proto == IPPROTO_TCP && packet->l7) {
622         struct tcp_header *th = packet->l4;
623
624         th->tcp_csum = recalc_csum32(th->tcp_csum, old_addr, new_addr);
625     } else if (nh->ip_proto == IPPROTO_UDP && packet->l7) {
626         struct udp_header *uh = packet->l4;
627
628         if (uh->udp_csum) {
629             uh->udp_csum = recalc_csum32(uh->udp_csum, old_addr, new_addr);
630             if (!uh->udp_csum) {
631                 uh->udp_csum = htons(0xffff);
632             }
633         }
634     }
635     nh->ip_csum = recalc_csum32(nh->ip_csum, old_addr, new_addr);
636     put_16aligned_be32(addr, new_addr);
637 }
638
639 /* Returns true, if packet contains at least one routing header where
640  * segements_left > 0.
641  *
642  * This function assumes that L3 and L4 markers are set in the packet. */
643 static bool
644 packet_rh_present(struct ofpbuf *packet)
645 {
646     const struct ovs_16aligned_ip6_hdr *nh;
647     int nexthdr;
648     size_t len;
649     size_t remaining;
650     uint8_t *data = packet->l3;
651
652     remaining = (uint8_t *)packet->l4 - (uint8_t *)packet->l3;
653
654     if (remaining < sizeof *nh) {
655         return false;
656     }
657     nh = ALIGNED_CAST(struct ovs_16aligned_ip6_hdr *, data);
658     data += sizeof *nh;
659     remaining -= sizeof *nh;
660     nexthdr = nh->ip6_nxt;
661
662     while (1) {
663         if ((nexthdr != IPPROTO_HOPOPTS)
664                 && (nexthdr != IPPROTO_ROUTING)
665                 && (nexthdr != IPPROTO_DSTOPTS)
666                 && (nexthdr != IPPROTO_AH)
667                 && (nexthdr != IPPROTO_FRAGMENT)) {
668             /* It's either a terminal header (e.g., TCP, UDP) or one we
669              * don't understand.  In either case, we're done with the
670              * packet, so use it to fill in 'nw_proto'. */
671             break;
672         }
673
674         /* We only verify that at least 8 bytes of the next header are
675          * available, but many of these headers are longer.  Ensure that
676          * accesses within the extension header are within those first 8
677          * bytes. All extension headers are required to be at least 8
678          * bytes. */
679         if (remaining < 8) {
680             return false;
681         }
682
683         if (nexthdr == IPPROTO_AH) {
684             /* A standard AH definition isn't available, but the fields
685              * we care about are in the same location as the generic
686              * option header--only the header length is calculated
687              * differently. */
688             const struct ip6_ext *ext_hdr = (struct ip6_ext *)data;
689
690             nexthdr = ext_hdr->ip6e_nxt;
691             len = (ext_hdr->ip6e_len + 2) * 4;
692         } else if (nexthdr == IPPROTO_FRAGMENT) {
693             const struct ovs_16aligned_ip6_frag *frag_hdr
694                 = ALIGNED_CAST(struct ovs_16aligned_ip6_frag *, data);
695
696             nexthdr = frag_hdr->ip6f_nxt;
697             len = sizeof *frag_hdr;
698         } else if (nexthdr == IPPROTO_ROUTING) {
699             const struct ip6_rthdr *rh = (struct ip6_rthdr *)data;
700
701             if (rh->ip6r_segleft > 0) {
702                 return true;
703             }
704
705             nexthdr = rh->ip6r_nxt;
706             len = (rh->ip6r_len + 1) * 8;
707         } else {
708             const struct ip6_ext *ext_hdr = (struct ip6_ext *)data;
709
710             nexthdr = ext_hdr->ip6e_nxt;
711             len = (ext_hdr->ip6e_len + 1) * 8;
712         }
713
714         if (remaining < len) {
715             return false;
716         }
717         remaining -= len;
718         data += len;
719     }
720
721     return false;
722 }
723
724 static void
725 packet_update_csum128(struct ofpbuf *packet, uint8_t proto,
726                      ovs_16aligned_be32 addr[4], const ovs_be32 new_addr[4])
727 {
728     if (proto == IPPROTO_TCP && packet->l7) {
729         struct tcp_header *th = packet->l4;
730
731         th->tcp_csum = recalc_csum128(th->tcp_csum, addr, new_addr);
732     } else if (proto == IPPROTO_UDP && packet->l7) {
733         struct udp_header *uh = packet->l4;
734
735         if (uh->udp_csum) {
736             uh->udp_csum = recalc_csum128(uh->udp_csum, addr, new_addr);
737             if (!uh->udp_csum) {
738                 uh->udp_csum = htons(0xffff);
739             }
740         }
741     }
742 }
743
744 static void
745 packet_set_ipv6_addr(struct ofpbuf *packet, uint8_t proto,
746                      ovs_16aligned_be32 *addr, const ovs_be32 new_addr[4],
747                      bool recalculate_csum)
748 {
749     if (recalculate_csum) {
750         packet_update_csum128(packet, proto, addr, new_addr);
751     }
752     memcpy(addr, new_addr, sizeof(*addr));
753 }
754
755 static void
756 packet_set_ipv6_flow_label(ovs_16aligned_be32 *flow_label, ovs_be32 flow_key)
757 {
758     ovs_be32 old_label = get_16aligned_be32(flow_label);
759     ovs_be32 new_label = (old_label & htonl(~IPV6_LABEL_MASK)) | flow_key;
760     put_16aligned_be32(flow_label, new_label);
761 }
762
763 static void
764 packet_set_ipv6_tc(ovs_16aligned_be32 *flow_label, uint8_t tc)
765 {
766     ovs_be32 old_label = get_16aligned_be32(flow_label);
767     ovs_be32 new_label = (old_label & htonl(0xF00FFFFF)) | htonl(tc << 20);
768     put_16aligned_be32(flow_label, new_label);
769 }
770
771 /* Modifies the IPv4 header fields of 'packet' to be consistent with 'src',
772  * 'dst', 'tos', and 'ttl'.  Updates 'packet''s L4 checksums as appropriate.
773  * 'packet' must contain a valid IPv4 packet with correctly populated l[347]
774  * markers. */
775 void
776 packet_set_ipv4(struct ofpbuf *packet, ovs_be32 src, ovs_be32 dst,
777                 uint8_t tos, uint8_t ttl)
778 {
779     struct ip_header *nh = packet->l3;
780
781     if (get_16aligned_be32(&nh->ip_src) != src) {
782         packet_set_ipv4_addr(packet, &nh->ip_src, src);
783     }
784
785     if (get_16aligned_be32(&nh->ip_dst) != dst) {
786         packet_set_ipv4_addr(packet, &nh->ip_dst, dst);
787     }
788
789     if (nh->ip_tos != tos) {
790         uint8_t *field = &nh->ip_tos;
791
792         nh->ip_csum = recalc_csum16(nh->ip_csum, htons((uint16_t) *field),
793                                     htons((uint16_t) tos));
794         *field = tos;
795     }
796
797     if (nh->ip_ttl != ttl) {
798         uint8_t *field = &nh->ip_ttl;
799
800         nh->ip_csum = recalc_csum16(nh->ip_csum, htons(*field << 8),
801                                     htons(ttl << 8));
802         *field = ttl;
803     }
804 }
805
806 /* Modifies the IPv6 header fields of 'packet' to be consistent with 'src',
807  * 'dst', 'traffic class', and 'next hop'.  Updates 'packet''s L4 checksums as
808  * appropriate. 'packet' must contain a valid IPv6 packet with correctly
809  * populated l[347] markers. */
810 void
811 packet_set_ipv6(struct ofpbuf *packet, uint8_t proto, const ovs_be32 src[4],
812                 const ovs_be32 dst[4], uint8_t key_tc, ovs_be32 key_fl,
813                 uint8_t key_hl)
814 {
815     struct ovs_16aligned_ip6_hdr *nh = packet->l3;
816
817     if (memcmp(&nh->ip6_src, src, sizeof(ovs_be32[4]))) {
818         packet_set_ipv6_addr(packet, proto, nh->ip6_src.be32, src, true);
819     }
820
821     if (memcmp(&nh->ip6_dst, dst, sizeof(ovs_be32[4]))) {
822         packet_set_ipv6_addr(packet, proto, nh->ip6_dst.be32, dst,
823                              !packet_rh_present(packet));
824     }
825
826     packet_set_ipv6_tc(&nh->ip6_flow, key_tc);
827
828     packet_set_ipv6_flow_label(&nh->ip6_flow, key_fl);
829
830     nh->ip6_hlim = key_hl;
831 }
832
833 static void
834 packet_set_port(ovs_be16 *port, ovs_be16 new_port, ovs_be16 *csum)
835 {
836     if (*port != new_port) {
837         *csum = recalc_csum16(*csum, *port, new_port);
838         *port = new_port;
839     }
840 }
841
842 /* Sets the TCP source and destination port ('src' and 'dst' respectively) of
843  * the TCP header contained in 'packet'.  'packet' must be a valid TCP packet
844  * with its l4 marker properly populated. */
845 void
846 packet_set_tcp_port(struct ofpbuf *packet, ovs_be16 src, ovs_be16 dst)
847 {
848     struct tcp_header *th = packet->l4;
849
850     packet_set_port(&th->tcp_src, src, &th->tcp_csum);
851     packet_set_port(&th->tcp_dst, dst, &th->tcp_csum);
852 }
853
854 /* Sets the UDP source and destination port ('src' and 'dst' respectively) of
855  * the UDP header contained in 'packet'.  'packet' must be a valid UDP packet
856  * with its l4 marker properly populated. */
857 void
858 packet_set_udp_port(struct ofpbuf *packet, ovs_be16 src, ovs_be16 dst)
859 {
860     struct udp_header *uh = packet->l4;
861
862     if (uh->udp_csum) {
863         packet_set_port(&uh->udp_src, src, &uh->udp_csum);
864         packet_set_port(&uh->udp_dst, dst, &uh->udp_csum);
865
866         if (!uh->udp_csum) {
867             uh->udp_csum = htons(0xffff);
868         }
869     } else {
870         uh->udp_src = src;
871         uh->udp_dst = dst;
872     }
873 }
874
875 /* Sets the SCTP source and destination port ('src' and 'dst' respectively) of
876  * the SCTP header contained in 'packet'.  'packet' must be a valid SCTP packet
877  * with its l4 marker properly populated. */
878 void
879 packet_set_sctp_port(struct ofpbuf *packet, ovs_be16 src, ovs_be16 dst)
880 {
881     struct sctp_header *sh = packet->l4;
882     ovs_be32 old_csum, old_correct_csum, new_csum;
883     uint16_t tp_len = packet->size - ((uint8_t*)sh - (uint8_t*)packet->data);
884
885     old_csum = sh->sctp_csum;
886     sh->sctp_csum = 0;
887     old_correct_csum = crc32c(packet->l4, tp_len);
888
889     sh->sctp_src = src;
890     sh->sctp_dst = dst;
891
892     new_csum = crc32c(packet->l4, tp_len);
893     sh->sctp_csum = old_csum ^ old_correct_csum ^ new_csum;
894 }
895
896 /* If 'packet' is a TCP packet, returns the TCP flags.  Otherwise, returns 0.
897  *
898  * 'flow' must be the flow corresponding to 'packet' and 'packet''s header
899  * pointers must be properly initialized (e.g. with flow_extract()). */
900 uint16_t
901 packet_get_tcp_flags(const struct ofpbuf *packet, const struct flow *flow)
902 {
903     if (dl_type_is_ip_any(flow->dl_type) &&
904         flow->nw_proto == IPPROTO_TCP && packet->l7) {
905         const struct tcp_header *tcp = packet->l4;
906         return TCP_FLAGS(tcp->tcp_ctl);
907     } else {
908         return 0;
909     }
910 }
911
912 const char *
913 packet_tcp_flag_to_string(uint32_t flag)
914 {
915     switch (flag) {
916     case TCP_FIN:
917         return "fin";
918     case TCP_SYN:
919         return "syn";
920     case TCP_RST:
921         return "rst";
922     case TCP_PSH:
923         return "psh";
924     case TCP_ACK:
925         return "ack";
926     case TCP_URG:
927         return "urg";
928     case TCP_ECE:
929         return "ece";
930     case TCP_CWR:
931         return "cwr";
932     case TCP_NS:
933         return "ns";
934     case 0x200:
935         return "[200]";
936     case 0x400:
937         return "[400]";
938     case 0x800:
939         return "[800]";
940     default:
941         return NULL;
942     }
943 }
944
945 /* Appends a string representation of the TCP flags value 'tcp_flags'
946  * (e.g. obtained via packet_get_tcp_flags() or TCP_FLAGS) to 's', in the
947  * format used by tcpdump. */
948 void
949 packet_format_tcp_flags(struct ds *s, uint16_t tcp_flags)
950 {
951     if (!tcp_flags) {
952         ds_put_cstr(s, "none");
953         return;
954     }
955
956     if (tcp_flags & TCP_SYN) {
957         ds_put_char(s, 'S');
958     }
959     if (tcp_flags & TCP_FIN) {
960         ds_put_char(s, 'F');
961     }
962     if (tcp_flags & TCP_PSH) {
963         ds_put_char(s, 'P');
964     }
965     if (tcp_flags & TCP_RST) {
966         ds_put_char(s, 'R');
967     }
968     if (tcp_flags & TCP_URG) {
969         ds_put_char(s, 'U');
970     }
971     if (tcp_flags & TCP_ACK) {
972         ds_put_char(s, '.');
973     }
974     if (tcp_flags & TCP_ECE) {
975         ds_put_cstr(s, "E");
976     }
977     if (tcp_flags & TCP_CWR) {
978         ds_put_cstr(s, "C");
979     }
980     if (tcp_flags & TCP_NS) {
981         ds_put_cstr(s, "N");
982     }
983     if (tcp_flags & 0x200) {
984         ds_put_cstr(s, "[200]");
985     }
986     if (tcp_flags & 0x400) {
987         ds_put_cstr(s, "[400]");
988     }
989     if (tcp_flags & 0x800) {
990         ds_put_cstr(s, "[800]");
991     }
992 }